Math.round vs hack

JavaScript performance comparison

Revision 6 of this test case created by Paul King

Info

Math.round() has a function call overhead, so using the ~~ hack (truncate towards 0) and adding 0.5 works quicker, but if you want to handle negative numbers too then you have to check whether to add or subtract 0.5 .... and this wipes out the speed advantage. So ~~(0.5+num) is only worth it if you know your numbers always have the same sign...

Preparation code

<script>
  function hack_round(n) {
   return~~ (0.5 + n);
  }
 
  var somenum = -500 + (Math.random() * 1000);
  var rounded;
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
"proper" rounding
rounded = Math.round(somenum);
pending…
Hack rounding
rounded = ~~ (0.5 + somenum);
pending…
Proper hack rounding
rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));
pending…
Hack with bitwise OR
rounded = (0.5 + somenum) | 0;
pending…
Hack with bitwise shift
rounded = (0.5 + somenum) << 0;
pending…
Hack rounding with call overhead
rounded = hack_round(somenum);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Miller Medeiros commented :

One thing that is interesting to note is that the newest browsers optimize function calls so much that there is no overhead of calling a function, in fact there is a performance gain... (I've seen it happening before as well)

Property look-up (e.g. foo.bar.lorem.ipsum) sometimes can still affect a little bit but even that doesn't change that much if the functions are called inside a loop and the object isn't updated during this time.

many things that used to be true about performance aren't anymore. The way that benchmarks are executed can influence the result, so the best thing is to test on the production code and make sure that those rules are still valid, sometimes it can perform completely different.

Christoph Bratschi commented :

Most of the test above are only valid for positive numbers. Negative numbers need different algorithms.

Add a comment