Math.floor divide 2 vs bit shift

JavaScript performance comparison

Revision 5 of this test case created by tomByrer

Info

added *0.5 test renamed tests

Preparation code

<script>

function caseDiv() {
  var sum = 0;
  for (var i = 0; i < 100; i++) {
    sum += Math.floor(i / 2);
  }
  return sum;
}

function caseShift() {
  var sum = 0;
  for (var i = 0; i < 100; i++) {
    sum += (i >> 1);
  }
  return sum;
}

function caseMul() {
  var sum = 0;
  for (var i = 0; i < 100; i++) {
    sum += Math.floor(i * 0.5);
  }
  return sum;
}
</script>
<script>
Benchmark.prototype.setup = function() {
    sum = -1;
};

Benchmark.prototype.teardown = function() {
    if (sum != 2450) throw "error";
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
mul
sum &= caseMul();
pending…
Bit shift
sum &= caseShift();
pending…
Math.floor *.5
sum &= caseMul();
pending…
div again
sum &= caseDiv();
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. Here’s a list of current revisions for this page:

0 comments

Add a comment