for循环和while循环哪个更快?
可能的重复:
while 或 for 哪个循环更快
我们可以使用 for 循环以及用于相同目的的 while 循环,速度更快,
例如:我想循环一个项目 1000000000 次,我应该使用 for 循环还是 while 循环?
它是迭代,那么为什么我们在编程中需要两者,只需要一个呢?
既然两个循环的工作原理相同,那么为什么我们需要两个循环呢?
Possible Duplicate:
What loop is faster, 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的编译器可能比您更聪明,并且会为您优化代码。所以通常你不必担心这类问题。如果您确实想知道,请对不同的方法进行基准测试,测量您感兴趣的参数,并根据基准测试的结果做出决定。
祝你好运!
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!
这两个循环大致等效。
您应该选择更适合您的代码的一种,即使代码更具可读性的一种。
例如,如果您的循环需要虚拟变量,那么 for 循环可能更合适。
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.
两者都足够快,使用更好地表达你的意图。
通常,如果“for”循环适用,则更可取,因为它表达了更特殊的含义(在容器或范围上迭代),因此信息更丰富。
如果您确实担心性能,请使用循环展开(多次重复循环体并减少迭代次数)或其他优化技术。对于现代优化编译器来说,语言结构之间的选择很少很重要。
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.