array.forEach running faster than native iteration? How?

javascript, performance, testing

Solution

There are many iteration optimizations that your `for` loop is missing such as:

- cache the array length

- iterate backwards

- use ++counter instead of counter++

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.

Problem

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

Original source

Related problems