Loops

JavaScript performance comparison

Revision 128 of this test case created by ASM

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 = [];
    var obj = {};
    for( var i = 0; i < 40; i++ ) {
        arr[ i ] = i+1;
        obj[ i ] = i+1;
    }
   
    // to let IE7 && other old browsers run this as well
    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) Old ’n’ busted for
for (var i = 0; i < arr.length; ++i) {
  arr[i];
};
pending…
02) Old ’n’ busted + length caching
for (var i = 0, len = arr.length; i < len; ++i) {
  arr[i];
};
pending…
03) Old ’n’ busted + var outside loop
var len = arr.length;
for (var i = 0; i < len; ++i ) {
  arr[ i ];
};
pending…
04) Reverse for
for (var i = arr.length; i--;) {
  arr[i];
};
pending…
05) while loop
var i = 0;
while (i < arr.length) {
  arr[i];
  i++;
};
pending…
06) while loop + length caching
var i = 0,
  len = arr.length;
while (i < len) {
  arr[i];
  i++;
};
pending…
07) Reverse while
var i = arr.length;
while (i--) {
  arr[i];
};
pending…
08) Reverse do … while loop
var i = arr.length;
do {
  arr[i];
} while (i--);
pending…
09) Cool guy loop + length caching
for (var i = -1, len = arr.length; ++i < len;) {
  arr[i];
};
pending…
10) Native forEach
arr.forEach(function(x) {
  x;
});
pending…
11) Native forEach with named function
function foo(x) {
  x;
};
arr.forEach(foo);
pending…
12) For In Array
for (i in arr) {
  arr[i];
};
pending…
13) For In Object
for (i in obj) {
  obj[i];
};
pending…
14) Object Property Accessor using Bracket notation
for( var i = 0; arr[i]; 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