For循环或While循环-效率 [英] For Loop or While Loop - Efficiency

查看:176
本文介绍了For循环或While循环-效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是while循环的效率与for循环的效率相比如何?一直有人告诉我,如果您可以使用for循环,那么我应该这样做.但是,实际上之间的区别是什么?

This may be a stupid question, but how does the efficiency of a while loop compare to that of a for loop? I've always been taught that if you can use a for loop, then I should. But what actually is the difference between :

$i = 0;
while($i < 100) {
     echo $i;
     $i++;
} 

比较:

for($i = 0; $i < 100; $i++) {
    echo $i;
}

我知道在这些特定示例中,差异约为.000000001%,但是当我们谈论大型复杂循环时,差异是什么?

I know in these specific examples the difference is like .000000001%, but when we are talking about large complex loops, what is the difference?

推荐答案

您可以从大多数答案中猜到,for循环相对while循环的主要优点是可读性. for循环更干净,看起来也更漂亮.使用while循环陷入无限循环也容易得多.我要说的是,我同意您的教that,即如果您可以使用for循环,则应该这样做,只要您坚持这样做,您的编程经验就会更加有趣.

As you can guess from most of these answers, the main advantage of a for loop over a while loop is readability. A for loop is a lot cleaner and a lot nicer to look at. It's also much easier to get stuck in an infinite loop with a while loop. I would say that I agree with your teachings that if you can use a for loop, you should, so as long as you stick to that, your programming experiences will be much more enjoyable.

这篇关于For循环或While循环-效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆