Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is more efficient in Javascript : while or for statements?

I recently got the opportunity to do looping in javascript and I was rather confused whether to use for loop or while statement.

 var i = foo.length;
 while(i--){

 }

or

 for(var i=0 ;i<=foo.length;i++){

 }

I want to know from javascript guys which one is more effecient to use and under what circumstances should we use them accordingly. Is it same reason as in java or someting different.

like image 670
user882196 Avatar asked Aug 14 '11 10:08

user882196


2 Answers

In theory the while loop is quicker because the for loop looks up the length attribute of foo every time though the loop, but in real-world use it's going to make an immeasurably small difference.

like image 139
RichieHindle Avatar answered Oct 06 '22 11:10

RichieHindle


In some browsers some ways of looping are faster - for example, in Chrome, the for loop is more than twice as fast, but there is no consistent winner across all browsers. If you find a trick to make it really fast in one browser, you will be punished for it in another browser.

Actual performance test in different browsers: http://jsperf.com/for-or-while

You should use the type of loop that makes sense for the situation. In many cases what you do inside the loop takes a lot longer than the loop itself.

like image 44
Guffa Avatar answered Oct 06 '22 13:10

Guffa