Math.round vs bitwise shift

Benchmark created by Jim Montgomery on


Description

Compare various ways of rounding.

Setup

var somenum = -500 + (Math.random() * 1000), rounded = 1000;

Teardown


    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);
  

Test runner

Ready to run.

Testing in
TestOps/sec
Math.round
rounded = Math.round(somenum);
ready
bitwise NOT
rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));
ready
bitwise OR
rounded = (somenum + (somenum > 0 ? .5 : -.5)) | 0;
ready
bitwise left shift
rounded = (somenum + (somenum > 0 ? .5 : -.5)) << 0;
ready
Math.round 2
rounded = Math.round(somenum);
ready
bitwise NOT 2
rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));
ready
bitwise OR 2
rounded = (somenum + (somenum > 0 ? .5 : -.5)) | 0;
ready
bitwise left shift 2
rounded = (somenum + (somenum > 0 ? .5 : -.5)) << 0;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Jim Montgomery on