The Developer Day | Staying Curious

Apr/08

16

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

3 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.

Leave a comment!

<<

>>

Find it!

Theme Design by devolux.org