Math.round vs hack (v55)

Revision 55 of this benchmark created by Ehsan Afzali on


Description

Test of different ways of rounding numbers, results vary a lot according to browsers and JS engines are getting smarter each day, so it is usually a better approach to don't try to be smarter than the engines and use the native feature (in this case, Math.round) since there is a bigger chance of performance improvements in the future and especially because bitwise operations reduces code readability.

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