For Loops

optimized for loops

by peterbenoit

JavaScript

var myarray = [];

// sub-optimal loop
for (var i = 0; i < myarray.length; i++) {
	// do something with myarray[i]
}

// optimization 1 - cache the length of the array with the use of `max`
for (var i = 0, max = myarray.length; i < max; i++) {
	// do something with myarray[i]
}


// optimization 2 - use single var pattern for consistency
// NOTE: A drawback is that it makes it a little harder to copy and paste whole loops while refactoring code.
var i = 0,
		max,
		myarray = [];

for (i = 0, max = myarray.length; i < max; i++) {
	// do something with myarray[i]
}


// optimization 3 - substitute `i++` with `i = i + 1`  or `i += 1` to avoid excessive trickiness
var i = 0,
		max,
		myarray = [];

for (i = 0, max = myarray.length; i < max; i += 1) {
	// do something with myarray[i]
}


// preferred 1
var i, myarray = [];
for (i = myarray.length; i--;) {
	// do something with myarray[i]
}	


// preferred 2
var myarray = [],
		i = myarray.length;
while (i--) {
	// do something with myarray[i]
}


// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/