Math.round vs hack (v5)

Revision 5 of this benchmark created by Miller Medeiros on


Preparation HTML

<script>
  var somenum = -500 + (Math.random() * 1000);
  var rounded;
  var round = Math.round; //cached
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
"proper" rounding
rounded = Math.round(somenum);
ready
Bitwise NOT
rounded = ~~ (0.5 + somenum);
ready
Proper hack rounding
rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));
ready
Bitwise OR
rounded = (0.5 + somenum) | 0;
ready
Bit shift left
rounded = (0.5 + somenum) << 0;
ready
Native casting
rounded = parseInt(0.5 + somenum)
ready
Bitwise AND
rounded = (0.5 + somenum) & (0.5 + somenum)
ready
Bitshift right
rounded = (0.5 + somenum) >> 0;
ready
Bitshift right (0 fill)
rounded = (0.5 + somenum) >>> 0;
ready
Bitwise XOR
rounded = (0.5 + somenum) ^ 0;
ready
Cached Reference
rounded = round(somenum);
ready
Math.floor
rounded = Math.floor(somenum + 0.5);
ready
Math.ceil
rounded = Math.ceil(somenum - 0.5);
ready

Revisions

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