Math.floor vs Math.round vs parseInt vs Bitwise vs Tilde

JavaScript performance comparison

Revision 129 of this test case created

Info

Rounding in all form possible

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var round = Math.round;
    var floor = Math.floor;
    var len = 100000;
    var values = [];
    while (len--) {
      values.push([Math.random() * len + 1, Math.random() * len + 1, Math.random() * len + 1]);
    }
    var index;
    var results = 0;
};

Benchmark.prototype.teardown = function() {
    results = 0;
};
</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
index = Math.floor(Math.random() * 100000);
results += Math.floor(values[index][0] / values[index][1]);
results += Math.floor(values[index][1] / values[index][2]);
results += Math.floor(values[index][2] / values[index][0]);
pending…
Math.round
index = Math.floor(Math.random() * 100000);
results += Math.round(values[index][0] / values[index][1]);
results += Math.round(values[index][1] / values[index][2]);
results += Math.round(values[index][2] / values[index][0]);
pending…
parseInt
index = Math.floor(Math.random() * 100000);
results += parseInt(values[index][0] / values[index][1]);
results += parseInt(values[index][1] / values[index][2]);
results += parseInt(values[index][2] / values[index][0]);
pending…
Bitwise |
index = Math.floor(Math.random() * 100000);
results += values[index][0] / values[index][1] | 0;
results += values[index][1] / values[index][2] | 0;
results += values[index][2] / values[index][0] | 0;
pending…
Bitwise
index = Math.floor(Math.random() * 100000);
results += values[index][0] / values[index][1] >> 0;
results += values[index][1] / values[index][2] >> 0;
results += values[index][2] / values[index][0] >> 0;
pending…
Tilde
index = Math.floor(Math.random() * 100000);
results += ~~(values[index][0] / values[index][1]);
results += ~~(values[index][1] / values[index][2]);
results += ~~(values[index][2] / values[index][0]);
pending…
Fast round
index = Math.floor(Math.random() * 100000);
results += round(values[index][0] / values[index][1]);
results += round(values[index][1] / values[index][2]);
results += round(values[index][2] / values[index][0]);
pending…
Fast floor
index = Math.floor(Math.random() * 100000);
results += floor(values[index][0] / values[index][1]);
results += floor(values[index][1] / values[index][2]);
results += floor(values[index][2] / values[index][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:

0 comments

Add a comment