Saturday, May 11, 2024
16
rated 0 times [  21] [ 5]  / answers: 1 / hits: 31560  / 11 Years ago, thu, september 5, 2013, 12:00:00

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?


More From » optimization

 Answers
48

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 < 20; ++k) {…}

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.


[#75870] Wednesday, September 4, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;