Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 315
user1015149 Avatar asked Jan 29 '13 08:01

user1015149


People also ask

What is the difference between local and global variables in PHP?

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.

What is the precedence when there are a global variable and a local variable in the program with the same name?

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.

What is the advantage of 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.

What is the difference between global and local variable?

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.


1 Answers

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.

like image 115
th3falc0n Avatar answered Sep 21 '22 00:09

th3falc0n