Loops

JavaScript performance comparison

Revision 129 of this test case created by Binyamin

Info

Array size = 40; Removed some obscure cases which were not faster on any of the platforms

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var arr = [];
   
    for(var i = 0; i < 40; i++) {
        arr[i] = i+1;
    }
   
    // Old browser legacy
    if (!Array.prototype.forEach) {
      Array.prototype.forEach = function(fun) {
        var len = this.length;
        for (var i = 0; i < len; ++i)
            fun(this[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
01) Naive "while" loop + length caching
var i = 0,
    len = arr.length;
while (i < len) {
    arr[i];
    i++;
}
pending…
02) Naive "for" loop
var i = 0;
for (; i < arr.length; i++) {
    arr[i];
}
pending…
03) Naive "for" loop + length caching
var i = 0,
    len = arr.length;
for (; i < len; i++) {
    arr[i];
}
pending…
04) Presave "for" loop
var i = 0;
for (; i < arr.length; ++i) {
    arr[i];
}
pending…
05) Presave "for" loop + length caching
var i = 0,
    len = arr.length;
for (; i < len; ++i) {
    arr[i];
}
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