I was wondering when does PHP free the memory which is used for a variables
for example
function foo(){
$foo = 'data';
return $foo; // <- is the memory space for `$foo` emptied at this point?
}
is it slower than:
function foo(){
return 'data';
}
?
Well, let’s find out!
Under PHP 5.3.6, my output is:
and then
It’s very likely that the memory increase during the initial calls to
demo1anddemo2that discard the output is due to the creation of variables to store memory use.However, the bottom line here is the two storage examples, where both returning data directly and assigning it to a variable before returning it resulted in the same exact memory use for the given data.
Conclusion: PHP seems smart enough in this simple test to not needlessly copy string variables — though do keep an eye on the memory use difference between the two functions. Just declaring the
demo1function took more memory that declaringdemo2. A few hundred bytes, really.