How to improve the performance of your for loops

Illustrate an abstract concept of code optimization.

Instead of the typical:

for(var i=0; i<theArray.length; i++)
{
     // Loop
}

Use:

for(var i=0, arrLen=theArray.length; i<arrLen; ++i )
{
     // Loop
}

Because instead of checking the length of the array each loop and comparing it to i, it stores it in a variable arrLen, which is then compared at each loop with i. This saves a few milliseconds, since checking the array length requires slightly more processing power.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top