Loops

JavaScript performance comparison

Revision 24 of this test case created by

Preparation code

<script>
   var arr = [];

   (function populateWithoutPollutingGlobalScope () {
      var k = 2000;
      while (k--) { arr[k]=k; }
   })();

   // Intentionally pollute all objects for the for-in test(s):
   Object.prototype [Number.MIN_VALUE] = "Externally polluted.";
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
 arr[i] *= 1;
 i++;
}
pending…
while loop that imitates a for loop, caching the length
var i   = 0
,   len = arr.length
;
while (i < len) {
 arr[i] *= 1;
 i++;
}
pending…
Reverse while loop
var i = arr.length;
while (i--) {
 arr[i] *= 1;
}
pending…
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
 arr[i] *= 1;
}
pending…
Reverse do … while loop
var i = arr.length - 1;
do {
 arr[i] *= 1;
} while (i--);
pending…
Reverse for loop
for (var i = arr.length; i--;) {
 arr[i] *= 1;
}
pending…
Old ’n’ busted for loop
for (var i = 0; i < arr.length; ++i) {
 arr[i] *= 1;
}
pending…
Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
 arr[i] *= 1;
}
pending…
Cool guy loop
for (var i = -1; ++i < arr.length;) {
 arr[i] *= 1;
}
pending…
Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
 arr[i] *= 1;
}
pending…
Native Array#forEach implementation
arr.forEach(function(x) {
 x *= 1;
});
pending…
Native Array#forEach implementation with named function
function foo(x) {
 x *= 1;
}
arr.forEach(foo);
pending…
for .. in (will skip empty values)
var i;

for (i in arr) {
   if (arr.hasOwnProperty (i) && isFinite (i)) {
      // Assured use of arr's elements vs. members like "length".
      arr[i] *= 1;
   }
}
pending…
i++
var l = arr.length
for (var i = 0, len = l; i < len; i++) {
 arr[i] *= 1;
}
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.

0 Comments