The Developer Day | Staying Curious



PHP lazy copy or copy on write

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.

RSS Feed

6 Comments for PHP lazy copy or copy on write

Jonathan Haddad | June 25, 2008 at 10:46 PM

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?

Author comment by admin | August 26, 2008 at 2:56 PM

No sorry :) Don’t have any official docs to back up the story. I found out this while reading the zend certification practice book.

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.

The HungryCoder | October 11, 2010 at 7:47 AM

Initially, I also thought like you too. Thanks for nice reference.

In PHP (>= 5.0), is passing by reference faster? - PHP Solution - Developers Q & A | July 24, 2013 at 11:53 AM

[...] and when you use a reference yourself, it incurs a little extra overhead. Can only find this mention at time of writing though, and comments in the manual contain other [...]

are arrays in php passed by value or by reference? - PHP Solution - Developers Q & A | July 25, 2013 at 9:19 AM

[...] FYI – this is known as “lazy copy” or “copy-on-write” – more info here: [...]

Leave a comment!



Find it!

Theme Design by