Programming Practices – Benefits of Using Extra Variables in For Loops

programming practices

I have found the following loop annotation in a big project I am working on (pseudocode):

var someOtherArray = [];
for (var i = 0, n = array.length; i < n; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}

What brought my attention is this extra "n" variable. I have never seen a for lop written in this way before.

Obviously in this scenario there is no reason why this code couldn't be written in the following way (which I'm very much used to):

var someOtherArray = [];
for (var i = 0; i < array.length; i++) {
    someOtherArray[i] = modifyObjetFromArray(array[i]);
}

But it got me thinking.

Is there a scenario when writing such a for loop would make sense? The idea comes to mind that "array" length may change during the for loop execution, but we don't want to loop further than the original size, but I can't imagine such a scenario.

Shrinking the array inside the loop does not make much sense either, because we are likely to get OutOfBoundsException.

Is there a known design pattern where this annotation is useful?

Edit
As noted by @Jerry101 the reason is performance.
Here is a link to the performance test I have created: http://jsperf.com/ninforloop. In my opinion difference is not big enough unless you are iterating though a very huge array. The code I copied it from only had up to 20 elements, so I think readability in this case outweighs the performance consideration.

Best Answer

The variable n ensures the generated code doesn't fetch the array length for every iteration.

It's an optimization that might make a difference in run time depending on the language used, whether the array is actually a collection object or a JavaScript "array", and other optimization details.

Related Topic