Math.round vs hack

JavaScript performance comparison

Revision 46 of this test case created by

Preparation code

<script>
var somenum = (Math.random());
var rounded;
var hackInFunction = function(num){
      return (num) | 0;
};
</script>
      
<script>
Benchmark.prototype.setup = function() {
  var othernum = (Math.random());
  var otherrounded;
  var hackInFunctionInProto = function(num){
        return (num) | 0;
  };

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Hack with bitwise shift
rounded = (0.5 + somenum) << 0;
pending…
Hack with bitwise OR large num first
rounded = (somenum + 0.5) | 0;
pending…
Proper hack rounding
rounded = ~~ (somenum + (somenum > 0 ? .5 : -.5));
pending…
Hack with bitwise OR
rounded = (0.5 + somenum) | 0;
pending…
"proper" rounding
rounded = Math.round(somenum);
pending…
Hack rounding
rounded = ~~ (0.5 + somenum);
pending…
rounded = hackInFunction(somenum + 0.5);
pending…
in setup?
otherrounded = Math.round(othernum);
pending…
in setup again?
otherrounded = (othernum + 0.5) | 0;
pending…
once again.
otherrounded = hackInFunctionInProto(othernum + 0.5)
pending…
outside inside
otherrounded = Math.round(somenum);
pending…
once agian inside my proto thingy magic sauce
otherrounded= ~~ (0.5 + othernum);
pending…

Compare results of other browsers

Revisions

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

0 Comments