Math.round vs bitwise shift

JavaScript performance comparison

Test case created by Jim Montgomery

Info

Compare various ways of rounding.

Preparation code

`` <script>  Benchmark.prototype.setup = function() {    var somenum = -500 + (Math.random() * 1000), rounded = 1000;  };  Benchmark.prototype.teardown = function() {    var round, or, not, left, result;    round = Math.round(somenum);    or = (somenum + (somenum > 0 ? .5 : -.5)) | 0;    not = ~~ (somenum + (somenum > 0 ? .5 : -.5));    left = (somenum + (somenum > 0 ? .5 : -.5)) << 0;    if(round == or && or == not && not == left) result = ('all values = '+round+' from: '+somenum);    else result = (['values do not match!','round:'+round,'or'+or,'not'+not,'left'+left, 'from:'+somenum].join('; '));    if(window.console && console.log) console.log(result);  };</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
Math.round
``rounded = Math.round(somenum);``
pending…
bitwise NOT
``rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));``
pending…
bitwise OR
``rounded = (somenum + (somenum > 0 ? .5 : -.5)) | 0;``
pending…
bitwise left shift
``rounded = (somenum + (somenum > 0 ? .5 : -.5)) << 0;``
pending…
Math.round 2
``rounded = Math.round(somenum);``
pending…
bitwise NOT 2
``rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));``
pending…
bitwise OR 2
``rounded = (somenum + (somenum > 0 ? .5 : -.5)) | 0;``
pending…
bitwise left shift 2
``rounded = (somenum + (somenum > 0 ? .5 : -.5)) << 0;``
pending…

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: