php 中哪个更快且占用资源更少?
For every
和 while
,推荐哪个更快,它们的资源使用情况如何?
Possible Duplicate:
for vs foreach vs while which is faster for iterating through arrays in php
For each
and while
, which of these is faster, recommended, and what are their resource usages like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
foreach
针对集合迭代进行了优化。这是一种奇特的说法,当您将它与数组(以及从 PHP5 开始,对象)一起使用时,它效果最好(也是最快)。您可以使用while()
获得与 foreach 相同的效果,但效率不高,因为您需要在while
内调用list()
代码>循环。用
while
编写的foreach($array as $key => $value)
是while(list($key,$value) = every($array ))
。您可以看到需要的额外呼叫数量。foreach
is optimized for iteration over collections. That's a fancy way of saying that it works best (and fastest) when you use it with arrays (and as of PHP5, objects). You can usewhile()
to get the same effect as a foreach, but its not as efficient since you need to calllist()
inside thewhile
loop.foreach($array as $key => $value)
written with awhile
iswhile(list($key,$value) = each($array))
. You can see the number of extra calls that are needed.我认为他们应该有相同的速度。
我更喜欢 foreach 因为它更安全。
i think they should have the same speed.
i prefer foreach because its safer.
这可能取决于您如何使用它们。您可以选择通过引用
foreach
循环来传递数组。在这种情况下,将不会复制整个数组。像这样的优化可能比在foreach
和while
之间进行选择更有效。That may depend on how you use them exactly. You can choose to pass an array by reference to the
foreach
loop. In that case there will not be made a copy of the entire array. Optimizations like this probably have more effect than choosing betweenforeach
andwhile
.