Four ways to floor a number in Javascript

Four ways to floor a number in Javascript

When I was developing my own HTML5 game engine, I needed to focus on performance to have the fastest processing of frames to draw. On of the most used methods within the drawing loop was rounding the pixel coordinates to avoid half pixel coordinates.

After some reading I figured out using floor() instead of round() could be a big performance gain. The most common known method to floor a number in Javascript is Math.floor() However there are three other less known methods which could be used instead. Some of them are faster than Math.floor().

This method uses double-not bitwise operator ~~ to round the number 9.5.

r = ~~9.5;

Another option is to use the bitwise or operatornot to confuse with the logical or which we use in our if statements.

r = 9.5|0

The third option is to use the Cached Math.Floor() function

r = f(9.5)

These three functions turned our to show different on performance when ran at jsperf.com

javascript-floor

As one can see the bitwise OR operator turned out to be the fastest. In daily use we could argue Math.floor() is sufficient and more readable. For the HTML5 game engine, which does a lot of floor operations every second, this is a performance gain.

Leave a Reply

Your email address will not be published. Required fields are marked *