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:
You can make it run faster by using a while loop instead.
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.