The Developer Day | Staying Curious

TAG | lazy-copy

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.

, , , Hide

Find it!

Theme Design by devolux.org