When looping through very large arrays, you may find this tip useful: it's much fast to use a while loop to iterate through an array than a for loop.

For example, if you take this code:

var myArray = new Array(10000);
for (var i=0; i<myArray.length; i++) {
  myArray[i] = i;
}

You can make it run faster by using a while loop instead.

var myArray = new Array(10000);
var n = myArray.length;
while (n--) {
  myArray[n] = n;
}

This works because n-- will return the value of n and then decrement it. So when it approaches index zero, it'll coerce 1 to true, then decrement n before the line myArray[n] = n;.

Of course, this while-loop is looping backwards, so if the order of iteration does matter then you can't use this method. You could however, still optimize the first example by first assigning myArray.length to a variable, then using that in the for-loop's exit condition. This will make it run slightly faster (depending on which browser you're using) because it avoids a property lookup at every loop iteration.

var myArray = new Array(10000);
var n = myArray.length;
for (var i=0; i<n; i++) {
  myArray[i] = i;
}


blog comments powered by Disqus