JS Optimisation #4 – For Loop II

, ,

In a previous post I covered optimising a for loop by using the assignation of a value as the test condition. In this post I take that a concept stage further.

When looping through an array, you normally perfom some kind of operation on each array item. Take this perfectly normal loop definition:

for (var i = 0, len = myArray.length; i < len; i++) {
	// ...do something with myArray[i]

Nothing wrong with that, but take some of the concepts mentioned in JS Optimisation #1 – For Loop and we can create a potentially slicker version:

for (var i = 0, myItem; myItem = myArray[i++];) {
	// do something with myItem

What we’re doing here is defining another variable at the beginning of the for loop to represent each array item, then in the test condition we’re attempting to assign it’s value to the next item in the array. If it succeeds, we continue, if not, we exit the loop.

So, what’s the benefit? Well, on the face of it there’s no real benefit at all, we still have to access the array item by using myArray[index], we’re just assigning the value to a variable in the second case. Okay, it looks a little funkier, but it doesn’t really gain you much. The real benefit to this approach comes when we access the array item more than once inside the loop. By having already assigned it to a variable, we only need perform the myArray[index] array accessing once and use the variable from then onwards, as opposed to repeatedly accessing the array item for every instance in which we use it.

I recently saw within the jQuery code that they use this approach (although typically inside while loops rather than for loops), so if it’s good enough for the jQuery team, it’s good enough for anyone!