PHP performance: $this->variable versus local $variable (manipulating)

北慕城南 提交于 2019-12-23 09:27:20

问题


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

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:

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

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

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

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?


回答1:


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.



来源:https://stackoverflow.com/questions/14578573/php-performance-this-variable-versus-local-variable-manipulating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!