UPDATE: Check out my last post on the matter: JavaScript Performance: JsPerf.com Myths

In this third post of this series dedicated to javascript performance I’m going to summarize the basic optimization steps for a loop:

  • Decrement iterators:
    As we saw in a previous post reversed loops are usually faster.

  • Make the terminal condition simpler:
    We also discussed about this in Javascript Performance: Loops 1. In short, the terminal condition is evaluated every time the loop iterates so make it work the faster you can.

  • Make the loop body simpler:
    No need to explain further here 😀

  • Use Post-test loops:
    Basically, for and while are pre-test loops and do-while is a post-test loop. Post-test loops evaluate the terminal condition at the end of the iteration and usually tend to run faster.

I have extended the jsperf test from the first post of the series just to include a post-test loop example so you can judge yourself

At the moment of writing this post jsperf seems to be down so I’m going to give you some javascript code for you to check it out on your own browsers:


//PREPARATION CODE
var arr = [];
for (var i = 0; i < 100000; i++) {
  arr.push({
    Number: i
  });
};
var res=[];

//NORMAL FOR
console.time('Normal for');
for(var i=0,len=arr.length;i<len;i++){
  res.push(arr[i]);
};
console.timeEnd('Normal for');
console.log(res.length);
res =[];

//REVERSED FOR
console.time('Reversed for');
for(var i=arr.length-1;i>=0;i--){
  res.push(arr[i]);
};
console.timeEnd('Reversed for');
console.log(res.length);
res =[];

//NORMAL WHILE
console.time('While');
var len = arr.length;
var i = 0;
while (i < len) {
  res.push(arr[i]);
  i++;
}
console.timeEnd('While');
console.log(res.length);
res =[];

//DO-WHILE
//This do-while loop is the FASTEST of all them.
console.time('Post-test');
var i=arr.length-1;
do{
    res.push(arr[i]);
}while(--i>=0);
console.timeEnd('Post-test');
console.log(res.length);
res =[];

//FOREACH
console.time('forEach');
arr.forEach(function(o){
	res.push(o);
});
console.timeEnd('forEach');
console.log(res.length);
res =[];

Check my Firefox console when testing this:
Firefox console showing test results

And here you can see my Chrome console:
Chrome console showing test results

Check this!
If you want to dig deeper on this matter I recommend you to get any of Nicholas C. Zakas’ books!.