PHP 中的 FOR 循环性能 [英] FOR loop performance in PHP

查看:55
本文介绍了PHP 中的 FOR 循环性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我的研究使我相信 for 循环是 PHP 中最快的迭代结构......更清楚地说,您认为以下哪个会更快?

As my research leads me to believe that for loops are the fastest iteration construct in PHP... to make it clearer, which of the following do you think would be faster?

for ($i = 0; $i < count($myLargeArray); $i++ ) {
    echo myLargeArray[$i];
}

示例二

$count = count($myLargeArray);
for ($i = 0; $i < $count; $i++ ) {
    echo myLargeArray[$i];
}

我的逻辑是,在示例一中的每次迭代中,在每次迭代中访问 myLargeArray 的长度比在示例二中访问简单的整数值在计算上更昂贵.对吗?

My logic follows that on each iteration in example one accessing the length of myLargeArray on each iteration is more computationally expensive than accessing a simple integer value as in example two. Is that correct?

推荐答案

第一种方法较慢,因为必须在循环的每次迭代中调用 count() 函数.count() 方法本身非常快,但是调用该函数仍然有一些开销.通过将其移出循环,您正在执行所谓的循环不变代码运动",或者有时提升".

The first way is slower because the count() function has to be called in every iteration of the loop. The count() method itself is pretty fast, but there is still some overhead in calling the function at all. By moving it outside the loop, you're performing what is called "loop invariant code motion", or sometimes "hoisting".

有一整套像这样的优化系列,值得学习.

There's a whole family of optimizations like this that are interesting to learn about.

说了这么多,很少有必要为此过分强调.在您的示例中,回显输出的 I/O 可能是您通过优化"节省的 10 倍.如果你在循环中做任何其他事情,你的优化意味着越来越少.

Having said all that, it seldom pays to stress about this very much. In your example here, the I/O of echoing the output is probably 10 times what you save through your "optimization". And if you do anything else at all inside your loop, your optimization means less and less.

我讨厌成为一个湿毯子,但对于超过 90% 的代码,性能不是问题.尤其是当您谈到 Web 应用程序时,它们的 I/O 超过 90%.

I hate to be a wet blanket, but for more than 90% of your code, performance is a non-issue. Especially when you talk about web applications, which are more than 90% I/O to begin with.

不过,当您认为应该归咎于您的代码时,您应该:

Still, when you think your code is to blame, you should:

  1. 确定您需要优化的用例
  2. 衡量您的代码性能
  3. 找出瓶颈
  4. 确定您可以改进的领域,并决定是否值得花时间改进它们.
  5. 更改代码
  6. 返回第 2 步

您几乎总是会发现您需要改进缓存策略和数据库优化(这只是另一种方式的 I/O 优化),而不是摆弄代码.

You'll nearly always discover that you need to improve your caching strategies and database optimization (which is just I/O optimization by another means), instead of twiddling code.

这篇关于PHP 中的 FOR 循环性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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