Many of us probably already know this:
var list = ...
var index = list.length
while( index-- ) {
// do something
}
It's supposedly the fastest way to do a loop in javascript since you avoid an extra test. So far, over the past years, I used this technique when dealing with data where speed was important and the order didn't really matter.
But now I stumbled upon an article that says this is actually slower when dealing with arrays.
Which makes you avoid an extra test (compared to the standard for loop). But you know what ? this will be much slower than using the right order. Because all CPU caches in the world expect the processing to be ‘straight’, you will have cache misses again and again, and a 2X slow down is what you’ll get when you are lucky.
So do not loop backward unless you have very good reasons to do so.
Source: https://gamealchemist.wordpress.com/2013/05/01/lets-get-those-javascript-arrays-to-work-fast/
Now I'm curious! I only have limited possibilities to test these things, and every other place I found still says that a backward loop is the fastest possible way (even multiple answers on stackoverflow). Is that really true when dealing with (possibly large) arrays?
And before the premature optimization answer pops up (like it often does with this type of question): This is mainly just curiosity and yes, in things like games, performance matters!
About jsperf: So far, jsperf seems to imply that the backward loop is faster (I can't check the tests right now since it doesn't load the result on any atm - so I'm recalling what I saw before). That's the source of this question: The two pieces of information are contradicting themselves - at least if that what's stated in that article is true! So what's "correct", in the end?