There are a bunch of variants on loops in that test and the results really surprised me:
|Browser||for loop, cached length||for loop, cached length, no callback||for loop, cached length, using function.call||for loop, reverse||for loop, simple||forEach||# Tests|
Here’s that data in a graph for Chome and Firefox just to make it a bit easier to visualise:
The other thing that stood out is that green bar in the middle, representing the ‘for loop, cached length using function.call’ which is the current method of looping I’m using because that what the libraries implement. The advantage of this approach is that it not only supplies each item in the array, it also gives the index and the full array as extra arguments and it allows me to specify an object to use for ‘this’ in the callback function. That’s all potentially very handy but I wasn’t actually taking advantage of it. Looks like switching to a custom ‘each’ implementation which uses the for loop with cached length approach should give a performance boost without making any other changes to the code so no sacrifice in maintainability.
- Use whatever for loop setup you want – it’s unlikely to affect overall performance in any noticeable way.
The Remaining Question
It’s all very well to learn these lessons, but since I’ve done all of this playing around in my own time at home, there’s a very significant problem with the results: they don’t include IE1. Since my real performance problems are worst on IE 6,7 and 8, I need to be running these tests there – it’s possible that changing the looping system really would yield performance gains in IE. I’ll have to try that out on Monday.