Math.round vs hack (v22)

Revision 22 of this benchmark created by icrusade on


Preparation HTML

<script>
  var mround = Math.round;
  var hround = function(n){
    return ~~ (0.5 + n)
  };
  var phround = function(n){
    return ~~ (n + (n > 0 ? .5 : -.5));
  };
  var orround = function(n){
    return (0.5 + n) | 0;
  };
  var shround = function(n){
    return (0.5 + n) << 0;
  };
  
  var somenum = -500 + (Math.random() * 1000);
  var rounded;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
"proper" rounding
rounded = mround(somenum);
ready
Hack rounding
rounded = hround(somenum);
ready
Proper hack rounding
rounded = phround(somenum);
ready
Hack with bitwise OR
rounded = orround(somenum);
ready
Hack with bitwise shift
rounded = shround(somenum);
ready

Revisions

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