Saturday, January 11, 2014

JavaScript Best Practices : loop optimization

You may also like to see:

As JavaScript is a client sided programming language, JavaScript should not do any complex or really difficult algorithms which take a lot of time computation.As it may cause to hang the browser or affect your site performance.


There are many things to optimize in a code, In this article I will try to discuss some techniques using we can optimize loops in JavaScript.



A simple loop in JavaScript is:



var fruits = ["apple","banana","orange","mango"];
for(var i = 0; i < fruits.length; i++) {
  // do something with fruits[i]
}

See Performance Demo here

This is simplest loop, we don't need to optimize it but if there are a huge number of items in the array to iterate on or there is complex logic in loop to implement, then we might need to make it faster. Following are some optimizations we can implement on this loop.  

Cache the condition to break

This loop will break when variable i is equals to length of the array, each time array checks this condition it will get the length from object, which is just a overhead. We can get the length of the array and assign it variable and use that variable so we don't need to calculate the length each time. This small trick is really beneficial when iterating over huge items.

var fruits = ["apple","banana","orange","mango"];  
for (var i = 0, max = fruits.length;i < max; i++) {    
   // do something with fruits[i] 
} 

See Performance Demo here

Now this will initialize once then it will use the max variable in each iteration.

(Note: Here initialization of i and max is separated with comma not semi-colan var i = 0, max = fruits.length;  

Single var Pattern

According to single var pattern:
Initializing all variable with single var at common place helps to control the scope of variables and avoiding collisions of variable names, unused variables or preventing logical issues due to uninitialized items. If there are 1000 variables and you initialized it with single var keyword, will save your more than 3000 characters which make your code lesser in size and make it even readable after minifying with some tool.

Using a single var for initialization of all the variable include in iteration can further optimize the performance, with a minor drawback of making copy-paste harder for a loop when refactoring a code.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i++) {
   // do something with fruits[i]
}

Making simplest increment  

i++ is a bit tricky operator what it actually do:
  • make a temporary copy of variable i
  • increment variable i
  • return the temporary copy for current use
so replacing this with i += 1 or i=i+1 will effect the loop positively.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i+=1) {
   // do something with fruits[i]
}

See Performance Demo here

Reverse loop

If we iterating over a loop for all the elements in a collection reverse loop starting from a length of collection to zero is faster than above given techniques, it completely depends on the situation whether to use this technique or not. As zero in JavaScript is equal to false so it will automatically break the loop on zero. In this technique condition testing and decrement is occurring in one step which making performance faster.

var i, fruits = ["apple","banana","orange","mango"]; 
for (i = fruits.length; i-=1;) {
   // do something with fruits[i]
}

See Performance Demo here

Making cleaner while-loop

If reverse loop iteration is possible then making it as while loop is more cleaner, it would not make code faster but will surely make it cleaner, readable, easy to understand.

var fruits = ["apple","banana","orange","mango"],i = fruits.length;
while(i-=1) {  //for readability use i--
   // do something with fruits[i]
}


See decrement operator performance difference here.

Summary

It is not necessary that you always get benefits from using these best practices as in small collection all above techniques might produce performance but when you are implementing complex algorithms with a number of collections then you will get the benefits of good code. So making it practice to use best practices always, will make your code and performance better even when you not realize it.


You may also like to see:

9 comments:

  1. Pls see:

    http://martinrinehart.com/frontend-engineering/engineers/javascript/arrays/array-loops.html

    The arithmetic loop should not be used for arrays.

    ReplyDelete
    Replies
    1. Martin I agree with you and your article is awesome!
      Zaheer Ahmed your article is very usefull, avoid i++ is a great tip! Thank you!

      Delete
  2. Can you provide some metrics on this?

    ReplyDelete
    Replies
    1. See performance test here : http://jsperf.com/loops-in-javascript-optimization-tricks/3

      Delete
  3. ch
    the last solution why not this:

    var fruits = ["apple","banana","orange","mango"],i = fruits.length;
    while(i-=1) {
    // do something with fruits[i]
    }

    or this:

    var fruits = ["apple","banana","orange","mango"],i;
    for(i in fruit){
    // do something with fruits[i]
    }


    but you know: the early size optimalizations are comes from the evil!!4!

    ReplyDelete
    Replies
    1. NEVER use for in on an array in javascript, this is not an optimization it is a mistake

      Delete
  4. Nice blog Zaheer.
    Here is what i got in favor of "for-loop"

    Advantages for-loop:
    • The for-loop will work parallel, for there is no dependency on jQuery.
    • High performance (for games, animations, simulation, dataware).
    • Full control over iterator (skips items, splice items from list, etc.).
    • Awareness syntax as utmost other related languages.

    Advantages $.each:
    • No concerns about scope (references to the iterator and object).
    • Can be used universally (for all types of objects , iterating over object keys).
    • Goes well in jQuery code (chaining and style).

    For live test and result:
    1. http://jsperf.com/fast-array-foreach
    2. http://jsfiddle.net/3ySng/1/

    ReplyDelete

Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,