Reputation: 959
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.
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!)
Upvotes: 2
Views: 980
Reputation: 2441
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.
Upvotes: 1