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...
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)
- Reverse While Loop
- The Cool Guy Loop
- Old and Busted Cached
- While Loop Cached
- The Cool Guy Loop Cached
- 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.
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.
No comments:
Post a Comment