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?
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$buntil$bgoes 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.