Blake Simpson

Fastest alternative to Math.floor in JavaScript

Wednesday 12th of March 2014

Normally to floor a number in JavaScript we would use the built in Math.floor function. There are however other ways to round a number down in JavaScript, by using the bitwise operators to perform the rounding operation on a binary level.

The various methods are:

  • |
  • ~~
  • <<
  • >>
  • >>>

Which can be used, for example, like so:

var float = 367.9987;

~~float //367
float | 0 //367
float << 0 //367
float >> 0 //367
float >>> 0 //367

I have set up a test on the great JS Perf website to sample which of these methods is fastest in the various browsers, check out the result and run the tests for yourself here:

http://jsperf.com/math-floor-alternatives

So far, my result graph looks like so (for an interactive version please visit the link above):

Math.floor results in JavaScript (from Browserscope)

These results are very interesting. As you can see currently Chrome will handle all of these operations at almost the same speed. However, Internet Explorer handles Math.floor around 76% slower than a bitwise shift/or.

Surprisingly Safari 7 handles all versions in a slow manner, with the triple bitwise shift (>>>) being the fastest.

In FireFox Math.floor has actually been optimised to the fastest but the other methods are still very close behind.

Taking all of this into account, I would suggest using a regular bitwise shift >> as this is fast in all browsers, including Internet Explorer.

However, that being said the syntax for a bitwise not is more intuitive and looks more natural in the flow of code, for example:

var x = 345.768,
  y = 0;

// Confusing
y = (5 * x) << 0;

// Nicer
y = ~~(5 * x);

// Least confusing, but slower
y = Math.floor( 5 * x );

So ultimately you must make the choice of which operation to use based on your application, the audience you have and the actual routine you are implementing. Meaning, it's best not to confuse the next programmer who comes along so Math.floor is best in non performance critical code but (5 * x) << 0; might be a good idea in a performance bottleneck situation such as on an animated <canvas> which runs code in a loop many times per second.

Read More Comments

Thanks for the programming challenge, Deutsche Telekom!

Saturday 15th of February 2014

A guide on how to fix the Speedport W 723V "web 'n' walk" configuration error that occurs when trying to run the setup.

Recently the W 723V Speedport router that I rent from Deutsche Telekom automatically pulled an update for new software. This update put my router into an unresponsive mode, meaning I had to reset the device and re-enter my login / configuration data through the internal configuration utility (A.K.A https://speedport.ip/).

The Speedport provides a configuration page where I would normally enter my Deutsche Telekom details and the setup would run. After this update however, the setup tells me that my "Web 'n' Walk Stick" has not been properly configured.

I do not own a Web 'n' Walk stick, so I saw this as an obvious bug in the configuration web page. The page was submitting the wrong configuration form details, as both forms are in the same page, just shown/hidden via JavaScript.

After calling Deutsche Telekom, they were clueless, had no help to give and promised to call back when an engineer was available. This is where I took the task upon myself to inspect the router software and see if I could fix this problem myself. The game was afoot, a programming challenge lay ahead. After around an hour absorbed in convoluted code, ignoring the temptation to let the Deutsche Telekom get away with this, I focused in on the problem, the following is the description of the solution.

Read More Comments

Photoshop: Creating a shadow effect

Friday 14th of February 2014

This is a tutorial on creating a shadow that will sit under an object to give a subtle raised effect. The final shadow will look like this:

Final Image

Read More Comments

FTP to a local wordpress install on OSX

Thursday 14th of November 2013

If you have the problem when working on a local wordpress installation where you need to do an upgrade or install a plugin, you may be presented with the following screen asking for FTP details to the server.

Wordpress plugin install FTP prompt

Lets assume you need to install a plugin. One option would be to manually download the plugin and move it into the wordpress plugins directory, but this is frustrating and slow. The better way is to let wordpress handle everything for you.

Read More Comments

Fix broken Apache and PHP after Mavericks upgrade

Tuesday 12th of November 2013

My Mac no longer had Apache or PHP working after the upgrade to Mac OSX 10.9, Mavericks. This is caused by the system upgrade removing the main configuration files for each service and creating backups instead.

Here are the steps I used to fix it, open a terminal window and use the following commands:

Fix Apache

cd /etc/apache2/
sudo mv httpd.conf httpd.conf.backup
sudo mv httpd.conf.pre-update httpd.conf
sudo apachectl restart

Once complete, Apache should be back up and running as before. Next, PHP can be repaired like so:

Fix PHP

cd /private/etc/
sudo mv php.ini-5.2-previous php.ini
sudo apachectl restart

That's it! These steps simply move the configuration files back to their correct location and restart the web server.

Notes:

  • I am assuming you use the original Apache/PHP install that comes with OSX, instead of a custom solution like MAMP.
  • Your PHP ini file may have a different name if you are not using version 5.2

Read More Comments

Google Analytics bug: Missing events with numeric labels

Monday 11th of November 2013

I have recently discovered a small bug in Google Analytics that prevents an event from being collected in the reporting if the event "label" is a number.

The situation I encountered this issue in was when using my Google Analytics Wrapper to track custom events. I had the 3rd label argument as the funnel step number that the visitor was currently on, it was simply an integer (1, 2, 3...) and after some waiting time I realised that Google Analytics was not accepting these events.

After testing I simply added a "step" prefix to the value, making it a string ("step-1") and the events immediately began recording as expected.

This may be a bug but may in fact be a method that Google uses to prevent a developer from tracking specific users, which is against the terms of service, where Google assume that an integer is a user ID or similar.

If anyone else has run into this issue and has any further insight, it would be great to hear.

Read More Comments

Easy CSS retina images (single image solution)

Tuesday 5th of November 2013

Here is a little trick that enables you to apply retina images to your web pages in pure CSS, no JavaScipt hacks or "-webkit" prefixes required!

The best part is that only a single retina image is required as opposed to requiring a "2x" and an unscaled version to be present in your project.

How to make a retina image

To begin with a "retina" image is required, which is just a buzz-word for an image that has double the normal resolution. You can create an image like this in Photoshop by making it twice the normal size (a 16x16 pixel icon would be 32x32 instead) and giving it a density of 144, rather than the default 72.

When saved, the file traditionally has "@2x" at the end of the filename and is in PNG format (e.g. "home-icon@2x.png").

CSS Integration

To apply the retina graphic to the web page, we use a solution that takes the double scaled retina image and resizes it to fit the unscaled version.

.home-icon {
  width: 16px;
  height: 16px;
  background-image: url("images/home-icon@2x.png");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 16px 16px;
}

This CSS snippet gives the icon a 16 pixel square size and we know the "home-icon@2x.png" image is 32 pixels square, so the background-size property fits them to match.

On a regular screen, everything will look normal, however on a "Retina" or other high resolution display, the icon will be displayed in it's true quality without any blur or defects.

The reasons I chose this solution are:

  • Pure CSS
  • Works across browsers
  • Works on mobile
  • Only requires a single image (efficient)

For an example, check out the differences of the image in this JS Fiddle on and off a high resolution display such as an iPhone: http://jsfiddle.net/UxK4N/

Read More Comments

Swipe.JS - Detect touch direction and distance

Friday 11th of October 2013

During development of recent project, I have had to realize a JavaScript solution that will detect when a visitor swipes the page and then perform an action based on the swipe direction and distance.

Of course this is not a new challenge and many solutions have already been found. jQuery mobile ships with a built in swipe event but I did not require such an extensive framework and decided to write the cleanest answer that solved the problem.

Below you will find the source code to a jQuery plugin I call "Swipe.JS", which provides the same swipe event to any DOM node.

Usage

First I will show how to use the plugin. Multiple swipe events can be bound to different nodes but for the sake of example, we will use the "body".

$("body").swipe(function( direction, offset ) {
  console.log( "Moving", direction.x, "and", direction.y );
  console.log( "Touch moved by", offset.x, "horizontally and", offset.y, "vertically" );    
});

Swipe.JS console output

Read More Comments