Here’s an interesting question from the Zend exam practice test:
“Absent any actual need for choosing one method over the other, does passing arrays by value to a read-only function reduce performance compared to passing them by reference?’
I wondered well PHP would have to make a copy of the variable passed so that would be slower than passing it by reference. I was wrong. Turns out PHP uses a lazy-copy mechanism (also called copy-on-write) that does not actually create a copy of a variable until it is modified. And since PHP must create a set of structures that it uses to maintain the reference it is actually “slower” to pass a variable to a read-only function by reference.
Having programmed for quite a few years I could have thought of that myself. Strangely this was not in the study guide.
3 Comments for PHP lazy copy or copy on write
Jonathan Haddad | June 25, 2008 at 10:46 PM
Kyle | July 2, 2009 at 7:00 PM
Jon: This comment may be a bit late, but if you just run some memory tests when copying variables, you will see that nothing extra is used until the data in the second variable is changed.
As the author said, it is actually slower to use the reference operator if you are only reading.


I’ve heard this before too, but I haven’t read it in any official docs. Do you have a link to any internal docs on the topic?