Performance of JavaScript Looping Techniques

I was reading Paul Irish’s (@paul_irish) recent blog post entitled Updates from all around – Dec 2009 and I saw an interesting for loop syntax that he referenced…

for (var i = -1, len = arr.length; ++i < len; ) // the cool guy loop

He went on further to show some performance results of the above syntax compared to the old for loop style most of us are used to.

I thought this was interesting, so I decided to put my own suite of tests together to exercise various looping techniques and determine their average performance. 

Note: In my test methods I wanted to simulate a semi-real world scenario where an array would be used and in the loop an item from the array would be referenced.

The test runner accepts the size of the array to be looped and the number of times you want the test to be ran. The end result will print the average time (in milliseconds) the test took to the console.

Here are the functions that I am profiling…

function oldAndBusted() {
for (var i = 0; i < arr.length; ++i) { arr[i]; }
}

function oldAndBustedCached() {
var arrLength = arr.length;
for (var i = 0; i < arrLength; ++i) { arr[i]; }
}

function coolGuyLoop() {
for (var i = -1, len = arr.length; ++i < len; ) { arr[i]; }
}

function coolGuyLoopCached() {
var arrLength = arr.length;
for (var i = -1, len = arrLength; ++i < len; ) { arr[i]; }
}

function whileLoopCached() {
var i = 0, arrLength = arr.length;
while (i < arrLength) { arr[i]; i++; }
}

function reverseWhileLoop() {
var i = arr.length;
while (i--) { arr[i]; }
}

Here are the results of my testing...

JavaScriptLoopPerformance2

You can view, run, and edit the tests for yourself on JS Bin (jsbin.com/uvoye/edit)

From a speed perspective here is how the various looping techniques ranked against each other (#1 being fastest & #6 being slowest)

  1. Reverse While Loop
  2. The Cool Guy Loop
  3. Old and Busted Cached
  4. While Loop Cached
  5. The Cool Guy Loop Cached
  6. Old and Busted
    I was actually surprised that ‘the cool guy loop cached’ was slower than ‘the cool guy loop’. I was thinking if I saved off the array length into a variable that it would speed up the loop instead of accessing the length every time.
    Note: If you have any variations of a loop you would like to see in my test cases, please provide a comment with your suggestion.

cooltext439924698 cooltext439925164

Note: The above performance times were ran using FireFox 3.6 Beta 4 using FireBug 1.5X.0b8 on an Intel Quad Core 2.00GHz Laptop running Win7.