php 中哪个更快且占用资源更少?

发布于 2024-10-09 10:32:55 字数 305 浏览 0 评论 0原文

可能的重复:
for vs foreach而在 php 中迭代数组速度更快

For everywhile,推荐哪个更快,它们的资源使用情况如何?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半夏半凉 2024-10-16 10:32:55

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 use while() to get the same effect as a foreach, but its not as efficient since you need to call list() inside the while loop.

foreach($array as $key => $value) written with a while is while(list($key,$value) = each($array)). You can see the number of extra calls that are needed.

新人笑 2024-10-16 10:32:55

我认为他们应该有相同的速度。
我更喜欢 foreach 因为它更安全。

i think they should have the same speed.
i prefer foreach because its safer.

不气馁 2024-10-16 10:32:55

这可能取决于您如何使用它们。您可以选择通过引用 foreach 循环来传递数组。在这种情况下,将不会复制整个数组。像这样的优化可能比在 foreachwhile 之间进行选择更有效。

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 between foreach and while.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文