CapelliC
CapelliC

Reputation: 60024

array argument passing: copy on write is implicit?

I wonder about the performance of array argument passing: it's worth to add the 'pass by reference' specifier to the argument to avoid the copy of the data, or such micro optimization is already implicitly implemented by the runtime ?

Let's say I have an array indexed by a not sequential key (of course). I've written this helper

function position_in_array($needle, &$haystack) {
    $k = array_search($needle, $haystack);
    return $k === false ? false : array_search($k, array_keys($haystack));
}

What I can see from documentation make me think that argument array copy could really be copy on write.

In case such hypothesis turns out to be correct, I will remove the 'by reference' specifier.

Upvotes: 0

Views: 86

Answers (1)

blue112
blue112

Reputation: 56462

PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting.

Yes, PHP uses copy on write.

You don't need to specify the & unless you need to modify the argument passed to your function (which implies you don't want copy on write, but real reference)

As N.B commented, it's taken from the manual, in the introduction to variables.

Upvotes: 2

Related Questions