Horizon88;10919113 wrote:...Passing by value has the overhead of allocating new memory, copying the value, then deleting it after it goes out of scope.
I was digging around and came across this article. In it, it describes what happens when variables are copied, references and whatnot. From what I gather (I'm still reading it), when a variable is copied, the value isn't copied, but rather, the 'other' variable merely points to the same zval (variable container) that the first variable points to (in order to save memory).
PHP tries to be smart when it deals with copying variables
like in $a = $b. Using the = operator is also called
an âassign-by-valueâ operation. While assigning by
value, the PHP engine will not actually create a copy of
the variable container, but it will merely increase the
refcount field in the variable container. As you can
imagine this saves a lot of memory in case you have a
large string of text, or a large array.
So what I am reading further down the page is that when passing by value, the only thing being done is a new symbol table is created ([along with a function stack] and thus destroyed upon return / exiting function scope).
So the idea is that when the new symbol table is created, the value is treated much like quoted above (in that the original and local function variable points to the same zval container). What I gather from this is that the only overhead is the creation / destruction of the symbol table as well as a function stack (but the zval container remains a single container that both variables point to.
In Figure 3, I illustrate exactly how variables are
passed to functions. In step 1, we assign a value to the
variable $a, againââthis isâ. We pass this variable to the
do_something() function, where it is received in the
variable $s. In step 2, you can see that it is practically
the same operation as assigning a variable to another
one (like we did in the previous section with $b = $a),
except that the variable is stored in a different symbol
tableâthe one that belongs to the called functionâ
and that the reference count is increased twice, instead
the normal once. The reason for this is that the functionâs
stack also contains a reference to the variable
container.
Granted, I'm no expert in how PHP handles variables.. but what I get from all this is that while there is some overhead in passing by value (which passing by reference doesn't involve), the actual value itself is not duplicated (assuming we are not making changes to the variable within the function - which in that case does create a new zval).