Search code examples
javascriptperformanceperformance-testingbitwise-operatorslogical-operators

Is it (still) the case that the bitwise AND operator is always faster than modulus for an odd number test?


I was doing some reading trying better to understand bitwise operators and came upon a helpful old blog post from 2012, which stated that - in an odd number test on a random, positive, integer x - evaluating x & 1 was 60% faster on the author's computer than evaluating x % 2. Stuff I've read elsewhere online (including on SO) seems to corroborate the bitwise operator being faster.

I've never written performance tests in jsperf before but I was interested to test this to see how much difference there was in Javascript. I was surprised to find, after testing across a few different browsers and devices, that modulo appeared to be faster more often than not.

Results

Chrome on Chromebook

Chrome on Chromebook

Chrome on Huawei P8

Chrome on Huawei P8

Chrome on Macbook Pro

Chrome on Macbook Pro

Firefox on Macbook Pro

Firefox on Macbook Pro

Safari on Macbook Pro

Safari on Macbook Pro

Safari on Macbook Air

Safari on Macbook Air

I ran each test a few times to check whether results were consistent. There were pretty consistent winners on FF and Chrome, although Safari did have more of a swing.

Since I have no experience in performance testing at all, have I written the tests badly wrong somehow? If not, could it be the case that modern devices and browsers somehow result in better performance for the modulus operator than for bitwise AND (or negligible difference in performance)? Is this even the appropriate way to benchmark this?

Or is there something else going on that I don't yet understand? (most likely!)


Solution

  • I think you've answered your own question. Is it ALWAYS the case? Clearly not. Like many other things with JavaScript, the results are heavily dependent on the browser as each has their own engine or implementation.