http://jsperf.com/testing-foreach-vs-for-loop
It was my understanding that Test Case 2 should run more slowly than Test Case 1 — I wanted to see how much more slowly. Imagine my surprise when I see it runs more quickly!
What’s going on here? Behind the scenes optimizaiton? Or is .forEach cleaner AND faster?
Testing in Chrome 18.0.1025.142 32-bit on Windows Server 2008 R2 / 7 64-bit
There are many iteration optimizations that your
forloop is missing such as:These are the ones that I have heard of and used, I am sure there are more. If memory serves me correct, the backwards iterating while loop is the fastest of all looping structures (in most browsers).
See this jsperf for some examples.
Edit:
links for postfix vs prefix perf test and iterating backwards.
I was not able to find my reference for using +=1 instead of ++, so I have removed it from the list.