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?
The main difference between Global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined.
If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.
If a variable is only needed in a single method then make it a local variable. The benefits are that you don't pollute larger namespaces unnecessarily, or larger execution contexts either. Variables should be declared in the smallest possible enclosing scope.
A global variable is a variable that is accessible globally. A local variable is one that is only accessible to the current scope, such as temporary variables used in a single function definition.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With