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:

//http://jsperf.com/math-floor-vs-bitwise
for (i = -10; i < 10; i += .01) {
  i > 0 ? ~~i : i == ~~i ? i : ~~i -1 === Math.floor(i) ? i : console.log("failed", i);
}

Then I came up with one for Math.round as well:

//http://jsperf.com/math-round-vs-bitwise-decimal
for (i = -5; i < 5; i += .01) {
  i > 0 ? i < ~~i + 0.5 ? ~~i : ~~i + 1 : i < ~~i - 0.5 ? ~~i - 1 : ~~i === Math.round(i) ? i : console.log("failed", i);
}

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!



Discussion:

blog comments powered by Disqus