0

Why the methods from Math is faster than the bitwise operators in Javascript?

For example:

  1. Math.floor vs | 0. ( http://jsperf.com/floor-vs-bitwise22 )
  2. Math.max vs a ^ ((a ^ b) & -(a < b)) ( http://jsperf.com/max-vs-bitwise-22 )
  3. Math.min vs b ^ ((a ^ b) & -(a < b)) ( http://jsperf.com/min-vs-bitwise-22 )

I want to know at implementation level, because executing something at bit level I thought I would jump all the translations and calls that a computer is gonna do to make what I want, at bit level, which is less cpu operations.

What's happening?

Acaz Souza
  • 7,905
  • 11
  • 52
  • 95
  • Can you show how you're calculating the timings? – Ash Burlaczenko May 13 '15 at 12:54
  • 3
    That depends on the browser engine... –  May 13 '15 at 12:55
  • Take also a look to https://stackoverflow.com/questions/4614768/javascript-math-ceilmath-abs-optimization – rpadovani May 13 '15 at 12:58
  • 1
    2 and 3 are obviously slower because you're performing much more in _JavaScript_, the question becomes _"Why is `Math.floor` faster than the `|` operator?"_, and comes down to both browser engine and maybe floor saves a little time by not needing to do a int32 conversion – Paul S. May 13 '15 at 13:08
  • 1
    Too many operations. Check this out: http://jsperf.com/max-vs-bitwise-22/2 – slebetman May 13 '15 at 13:09
  • 1
    A simple implementation of Math.max (or Math.min) uses just one comparison to get at the answer. Your code uses 5 calculations. – Hans Kesting May 13 '15 at 13:09
  • Also remember that min/max is not limited to two arguments... –  May 13 '15 at 13:28

1 Answers1

1

… I thought I would jump all the translations and calls that a computer is gonna do …

Modern optimizing JavaScript engines can perform surprising optimizations. In this case, I'd guess that the Math calls simply get inlined.

If you really want to know what's going on, and not just guess, then you'll have to look at the end product of what your optimizer generates. See e.g. How can I see the machine code generated by v8? for details on that.

Community
  • 1
  • 1
MvG
  • 54,493
  • 18
  • 133
  • 262