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

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

问题描述

正如我的研究使我相信循环是PHP中最快的迭代构造...为了使它更清晰,您认为以下哪一个更快?



示例一



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





示例二



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





$ b我的逻辑如下所示:在每个迭代中,访问myLargeArray的长度每个迭代在计算上比在例2中访问一个简单的整数值要昂贵得多。第一种方法比较慢,因为 count()是正确的吗?函数必须在循环的每一次迭代中被调用。 count()方法本身是相当快的,但是在调用函数时仍然有一些开销。通过将其移动到循环之外,即可执行所谓的循环不变代码运动 ,或者有时是吊起来。



整个这样的优化系列,这是有趣的学习。

说了这么多,很少有人会非常重视这一点。在你的例子中,回显输出的I / O大概是你通过优化保存的10倍。如果你在循环中做任何事情,你的优化意味着越来越少。



我讨厌成为一个湿的毯子,但是超过90%代码,性能是一个非问题。特别是当你谈论的Web应用程序,这是超过90%的I / O开始。



但是,当你认为你的代码是怪,你应该:
$ b


  1. 决定你需要优化的用例

  2. 测量你的代码性能

  3. 查找瓶颈

  4. 识别您可以改进的区域,并决定是否值得花时间改进它们。更改您的代码

  5. 返回步骤2

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

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?

Example ONE

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

Example TWO

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

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?

解决方案

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.

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.

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. Decide on the use case you need to optimize
  2. Measure your code performance
  3. Find the bottlenecks
  4. Identify the areas you can improve and decide whether it is worth your time to improve them.
  5. Make your code changes
  6. Go back to step 2

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.

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

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