Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

optimization - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...