dkinzer dkinzer - 3 months ago 7
PHP Question

Does referencing a variable in a php function help save memory?

For example are the following two functions the same or not when one compares how memory is being managed:

$hello = 'hello';

my_echo($hello);

//Better or worse than
my_echo_ref($hello);

//case 1, no referencing:
function my_echo($word) {
echo $word;
}

//case 2, referencing:
function my_echo_ref(&$word) {
echo $word;
}

Answer

I don't know how reliable this source is, but this is a very interesting article (from 2008) that explains how variables are handled:

The Truth About PHP Variables

It says

I wanted to write this post to clear up what seems to be a common misunderstanding in PHP – that using references when passing around large variables is a good way save memory.

and

(...) While the above explanation of references is sufficient for a general understanding, it is often useful to understand how PHP handles variable assignment internally. This is where we introduce the concept of the zval.

zvals are an internal PHP structure which are used for storing variables. Each zval contains various pieces of information, and the ones we will be focusing on here are as follows:

  • The actual data stored within the zval – In our example this would be either ‘hello!’ or ‘goodbye!’
  • is_ref Boolean flag
  • A ref_count counter

(...)

and

(...) When you assign a variable by value (such as in example 1) it does not create a new zval, it simply points both variables at the same zval and increases that zval’s ref_count by one. “Wait!” I hear you cry, “Isn’t that passing by reference?” Well, although it sounds the same, all PHP is doing is postponing any copying until it really has to – and it knows this because is_ref is still false. (...)

and the conclusion:

You can see that, unless the developer is completely consistent, passing variables by reference can easily lead to increased memory usage.


Besides that, I ran your code a few times with get_memory_usage() and there was no difference in memory consumption (but this does not necessarily mean anything, probably the memory consumption differs when one is actually doing something with the variable).