Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Performance: While vs For Loops

The other day during a tech interview, one of the question asked was "how can you optimize Javascript code"?

To my own surprise, he told me that while loops were usually faster than for loops.

Is that even true? And if yes, why is that?

like image 204
Mr_Pouet Avatar asked Sep 05 '13 15:09

Mr_Pouet


People also ask

Is while loop faster than for loop in JavaScript?

For loops are trivially faster than while loops.

Do-while loops run faster than for loops?

The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.

ARE FOR loops in JavaScript slow?

Notes. You should never use “ for-in” to iterate over members of an array. Each iteration through this loop causes a property lookup either on the instance or on the prototype, which makes the for-in loop much slower than the other loops. For the same number of iterations, it could be seven-time slower than the rest.

Which loop is faster in JavaScript?

The fastest loop is a for loop, both with and without caching length delivering really similar performance.


1 Answers

You should have countered that a negative while loop would be even faster! See: JavaScript loop performance - Why is to decrement the iterator toward 0 faster than incrementing.

In while versus for, these two sources document the speed phenomenon pretty well by running various loops in different browsers and comparing the results in milliseconds: https://blogs.oracle.com/greimer/entry/best_way_to_code_a and: http://www.stoimen.com/blog/2012/01/24/javascript-performance-for-vs-while/.

Conceptually, a for loop is basically a packaged while loop that is specifically geared towards incrementing or decrementing (progressing over the logic according to some order or some length). For example,

for (let k = 0; ++k; k < 20) {…} 

can be sped up by making it a negative while loop:

var k = 20; while (--k) {…} 

and as you can see from the measurements in the links above, the time saved really does add up for very large numbers.

like image 189
Chris Marie Avatar answered Oct 14 '22 15:10

Chris Marie