There are probably as many ways of looping an array in javascript as there are phrases that are synonymous for masturbation. So, what are they and how fast do they perform? Head over to this test @ a blog on Sun which sports no less than 17 different loops to get a fair indication of how fast things work in today’s browsers.
Disappointingly, the native array.forEach in my firefox 2.5 seems to be one of the worst results. while(length–) { … } ftw!
WOW!!
Very expressive results which makes it clear what i will be using from now on 🙂
sometimes, you don’t have a choice though. for instance–doing a for … in loop to iterate through an array (treating it as an object instead) is the only way to obtain the array keys. This works due to Array in javascript actually being an object with array-type characteristics but it’s dangerous due to prototypical inheritance of the Array itself – any changes to that would show up as members of your array so you also need to use ‘hasOwnProperty()’ and it adds even more time to the loop