PHP性能:$ this->变量与本地$ variable(操作) [英] PHP performance: $this->variable versus local $variable (manipulating)

查看:148
本文介绍了PHP性能:$ this->变量与本地$ variable(操作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个班级的一个部分决定拆分为一个新部分.

I had a section in a class that I decided to split into a new one.

当我将代码段移植到新类中时,我注意到执行foreach循环之一的速度相当慢.

When I had ported the code section into a new class I noticed it was considerably slower at executing one of the foreach loops.

我设法找出问题的一部分,以决定保存最终结果数组的方式.

I managed to track down part of the problem to be how I decided to save the final result array.

如果您看到我的代码的简化版本,我认为它会更容易理解:

I think it'll be easier to understand if you see a shortened version of my code:

原始的移植代码: http://pastebin.com/2iBuqmgn 更优化的移植代码: http://pastebin.com/TYU1rHwU

The original ported code: http://pastebin.com/2iBuqmgn More optimized ported code: http://pastebin.com/TYU1rHwU

您将看到在第一个示例中,我一直在整个过程中直接操作$ this-> active_topics.

You'll see that in the first example I manipulate $this->active_topics directly all the way trough.

在第二个示例中,我在使用foreach循环之后将局部变量保存到$ this-> active_topics之前使用了局部变量.

While in the second example I use local variables before I save the local variable to $this->active_topics AFTER the foreach-loop.

在原始循环中,循环似乎平均达到1秒,而最优化的循环则平均使用0.85执行一次.他们最终返回的内容完全相同.

With the original a loop seemed to average to 1 second, while the more optimized one use 0.85 to execute on average. They end up returning exactly the same content.

为什么使用局部变量的优化代码更有效?

Why is the more optimized code, with use of local variables, more efficient?

推荐答案

当您访问类中的某些内容时,PHP解释器首先必须在内存中找到该类,然后查看该属性在哪里.在普通的局部变量上,不需要在类内搜索属性,它可以直接访问变量的内存,因此速度更快一些.

When you access something in a class the PHP interpreter first has to find the class in memory and then look where the attribute is. On a plain local variable it doesn't need to search the attribute inside the class it can just access the memory of the variable directly and so it is a little faster.

这篇关于PHP性能:$ this->变量与本地$ variable(操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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