Math.floor divide 2 vs bit shift
JavaScript performance comparison
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.
Test  Ops/sec  

Math.floor /2 

pending… 
Bit shift 

pending… 
Math.floor *.5 

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:
 Revision 1: published by Ed Sanders
 Revision 2: published
 Revision 3: published by tomByrer
 Revision 7: published
 Revision 8: published
 Revision 9: published
 Revision 10: published
2 comments
tomByrer (revision owner) commented : ∞
Odd how on the same computer, Chrome's results for .floor(i/2) & shift are so close, but have a big gap on Firefox?!? I would assume from this test that Chrome optimizes this case. Firefox gives the behavior I expect, since divides take up fewer CPU cycles than multiply, but 2 math functions will be slower than 1 (shift).
Results: UserAgent Bit shift Math.floor /2 Math.floor *.5 # Tests Chrome 24.0.1312 4,688,830 4,683,492 2,435,539 4 IE 8.0 22,990 25,716 26,855 3 Pale Moon (Firefox Variant) 19.0.2 5,392,935 2,165,562 2,500,029 2
tomByrer (revision owner) commented : ∞
Ran on my Note 2 (Sprint); found the bitshift vs .floor(i/2) ratio to be around what I expected (2:1), but .floor(i*.5) is still too much slower.
UserAgent Bit shift Math.floor /2 Math.floor *.5 # Tests Android 4.1.2 2,457,734 1,230,498 409,705 3