Math Floor Math Round With Bitwise Operators
28 October 2011
James Padolsey’s article on the bitwise NOT inspired me to research if the “doesn’t work for negative numbers” thing would have an easy workaround and if that workaround would allow us to still calculate faster than the Math.floor function.
I came up with this test to replace Math.floor:
Then I came up with one for Math.round as well:
Each one will out-perform the peer Math function (your browser’s mileage may vary). See the JSPerf links here and here.
As a colleague pointed out, if you make these expressions into a function for reuse, the Math functions will out perform them or, at worst, break even.
So, really the only time you might want to use this is in a performance-critical application (like animation). But it’s still cool!