Math.floor vs shift 2

JavaScript performance comparison

Revision 2 of this test case created

Info

Compares Math.floor(x) to (x >> 0) as a way of converting to an int. They aren't completely equivalent; note that Math.floor(NaN) is NaN, while (NaN >> 0) is 0. Also added a if NaN function.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function a(num) {return Math.floor(num);}
    function b(num) {return +num>>0;}
    function c(num) {num=+num;return num===num?num>>0:NaN;}
    function d(num) {if(+num===NaN)return NaN;return num>>0;}
    function e(num) {return Number(Number(num)>>0)}
    function f(num) {return Number(num)===num?num===""?0:num>>0:NaN;}
};
</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
Math.floor
a(10*Math.random())
pending…
Shift
b(10*Math.random())
pending…
Shift with Ternary
c(10*Math.random())
pending…
Shift with If
d(10*Math.random())
pending…
Shift with Number Conversion
e(10*Math.random())
pending…
Shift with number coercion 2
f(10*Math.random())
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