Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top