Always cache the length property in for loops when using JavaScript

By David Pratt / Tags: , , / No Comments / Published: 26-01-10

To speed up for loops in JavaScript you should always look to cache the length property so that the value of this doesn’t have to be recalculated on every iteration of the loop. There are a couple of ways to do this, the first and most obvious way is to calculate the array length outside of the loop e.g.

var l = bigArray.length;
for(var i = 0; i < l; i++){
	//Do stuff

Another less well known way is to cache the length property in the for loop decleration e.g.

for(var i = 0, l = bigArray.length; i < l; i++){
	//Do stuff

Category: Tech

Tags: , ,

Posted: on January 26th, 2010 at 12:13 pm.

Feeds: RSS 2.0

Leave a reply