开发者

for loop or while loop which is faster? [duplicate]

开发者 https://www.devze.com 2023-02-06 12:55 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: What loop is f开发者_开发知识库aster, while or for
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What loop is f开发者_开发知识库aster, while or for

we can use for loop as well as while loops for same purpose which is faster

for eg: i want to loop an item 1000000000 times shall i use for loop or while loop?

it is iteration then why do we need both in programing only one is needed?

since both loops are working same then why do we need both?


Your compiler is probably smarter than you and will optimze the code for you. So usually you don't have to bother these kind of problems. If you really want to know, benchmark different approaches, measure the parameters you're interested in and make a decision based on the results of the becnhmark.

Good luck!


The two loops are roughly equivalent.

You should just chose the one that is more appropriate for you code i.e. the one that makes the code more readable.

For example if your loop requires a dummy variable then a for loop maybe more appropriate.


It is literally the same. Translation in machine language of both things is usually the same.


both are fast enough, use what better express your intent. Usually, if "for" loop is applicable, it is preferable because it express more special meaning (iteration over a container or range) and, therefore, is more informative.

if you are really worry about performance use loop unwinding (repeat loop body several times and reduce number of iterations) or other optimization technics. Choosing between language constructions rarely matters for modern optimized compilers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号