Reputation: 2441
Is there a performance/resources difference between these two?
$a = "foo bar";
$b = substr($a,-3);
if ($b == "bar")
{
echo "bar!!";
}
and
if (substr($a = "foo bar", -3) == "bar")
{
echo "bar!!";
}
In the first one you are using an extra variable, I always do this for making it more readable, and also making it possible to know the value when debugging, I don't like to do any processing in my conditions, does this really matter performance wise? am I using more memory?
I'd like to see how these two differ theoretically and practically, should one avoid using unecessary variable assignments?
Upvotes: 2
Views: 261
Reputation: 46040
In this case your just splitting hairs. So no it doesn't matter.
Also, if you are in the scope of a function, then the variables will just get garbage collected after the function returns.
Upvotes: 0
Reputation: 75130
The only difference (besides a difference in the AST and/or bytecode) is that when you do $b = substr($a, -3)
, you keep the returned string in $b
until $b
goes out of scope, then the reference is released and the string can then be garbage collected.
When you do it the the other way, the string is used in the comparison to "bar"
and then is immediately discarded so the garbage collector can clean it up sooner.
Will this make a difference to you? No. Don't take it into account because it can't be overstated how small a thing it is. Code for clarity.
Upvotes: 4
Reputation: 36512
In theory, yes, fewer variables means the program uses less memory which could lend itself to better performance. However this is such a minute point, given the processing power available and the nature of PHP. It's intended to be a scripting/programming language for speed, not extreme performance. Do what's most readable, that gets the job done in the least amount of your time, not the CPU's.
Upvotes: 1