Faster Javascript loops

Consider this very standard construct:

//assume arr is an array
for (var i = 0, i < arr.length; i++)
{
...
}

This is extemely inefficient because the "length" property needs to be looked up on each pass through the loop. One easy fix is to first define a variable for the length, like this:

var l = arr.length;
for (var i = 0; i < l; i++)

This is an improvement, but this particular loop is so simple that it could be further simplified into a while loop, which will run much faster again. Since we don't really care whether we go through the array from its beginning to end or vice versa:

var i = arr.length;
while (i--)
{
...
}

This little tip applies to Javascript in general but will be highly effective with DXStudio scripting. Also, I cannot take credit for this discovery. I read it on Sitepoint.

Leave a Comment

You must be logged in to post a comment.