Loops (v24)

Revision 24 of this benchmark created on


Description

Compares speed of variations of the for, for-in, while, do-while, and Array.forEach looping constructs.

Changes since revision 22

: Fixed the "Reverse dowhile loop" test so it doesn't make the arr array larger for later tests.

: Normalized operation complexity to arr[i] *= 1 for all tests so later iteration of tests aren't doing calculations with larger values (i.e. 1998 * 5 => 9,990 * 5 => 49,950).

: Fixed the "for .. in (will skip empty values)" test so it only uses arr's elements and excludes standard and injected Array members.

: Fixed the Preparation code so it doesn't leak its local "k" loop counter variable into the global scope.

Preparation HTML

<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

Ready to run.

Testing in
TestOps/sec
while loop that imitates a for loop
var i = 0;
while (i < arr.length) {
 arr[i] *= 1;
 i++;
}
ready
while loop that imitates a for loop, caching the length
var i   = 0
,   len = arr.length
;
while (i < len) {
 arr[i] *= 1;
 i++;
}
ready
Reverse while loop
var i = arr.length;
while (i--) {
 arr[i] *= 1;
}
ready
Reverse while loop without implicit ToBoolean
var i = arr.length;
while (i-- > 0) {
 arr[i] *= 1;
}
ready
Reverse do … while loop
var i = arr.length - 1;
do {
 arr[i] *= 1;
} while (i--);
ready
Reverse for loop
for (var i = arr.length; i--;) {
 arr[i] *= 1;
}
ready
Old ’n’ busted for loop
for (var i = 0; i < arr.length; ++i) {
 arr[i] *= 1;
}
ready
Old ’n’ busted for loop, caching the length
for (var i = 0, len = arr.length; i < len; ++i) {
 arr[i] *= 1;
}
ready
Cool guy loop
for (var i = -1; ++i < arr.length;) {
 arr[i] *= 1;
}
ready
Cool guy loop, caching the length
for (var i = -1, len = arr.length; ++i < len;) {
 arr[i] *= 1;
}
ready
Native Array#forEach implementation
arr.forEach(function(x) {
 x *= 1;
});
ready
Native Array#forEach implementation with named function
function foo(x) {
 x *= 1;
}
arr.forEach(foo);
ready
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;
   }
}
ready
i++
var l = arr.length
for (var i = 0, len = l; i < len; i++) {
 arr[i] *= 1;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.