Math.floor vs Math.round vs parseInt vs Bitwise

JavaScript performance comparison

Revision 126 of this test case created by PAEz

Info

Rounding in all form possible and not-not

PAEz: All the previous tests I looked at had hard coded values that dont change....this makes me worry that it'll get optimized, so I added in something to try and stop that.....seems to kill Math.round in Chrome, wonder why?

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var numbers=[];
    var numbersCount=5000;
    for (var i=0,iend=numbersCount;i<iend;i++) numbers.push(Math.random*i);
};
</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
for (var i=0;i<numbersCount;i++){
var z = Math.random();
z += Math.floor(numbers[i]);
}
pending…
Math.round
for (var i=0;i<numbersCount;i++){
var z = Math.random();
 z += Math.round(numbers[i]);
}
pending…
parseInt
for (var i=0;i<numbersCount;i++){
var z = Math.random();
z += parseInt(numbers[i]);
}
pending…
Bitwise |
for (var i=0;i<numbersCount;i++){
var z = Math.random();
z += numbers[i] | 0;
}
pending…
Bitwise
for (var i=0;i<numbersCount;i++){
var z = Math.random();
z += numbers[i] >> 0;
}
pending…
Not not
for (var i=0;i<numbersCount;i++){
var z = Math.random();
z += ~~(numbers[i]);
}
pending…
Math.round Equivalent
for (var i=0;i<numbersCount;i++){
var z = Math.random();
z += (numbers[i]+0.5) | 0;
}
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:

1 comment

PAEz (revision owner) commented :

You still suck IE!!!!!!!!!!!!!!!!!!!

Add a comment