In PHP (>= 5.0), is passing by reference faster?

Viewed 34827

In PHP, function parameters can be passed by reference by prepending an ampersand to the parameter in the function declaration, like so:

function foo(&$bar)
{
    // ...
}

Now, I am aware that this is not designed to improve performance, but to allow functions to change variables that are normally out of their scope.

Instead, PHP seems to use Copy On Write to avoid copying objects (and maybe also arrays) until they are changed. So, for functions that do not change their parameters, the effect should be the same as if you had passed them by reference.

However, I was wondering if the Copy On Write logic maybe is shortcircuited on pass-by-reference and whether that has any performance impact.

ETA: To be sure, I assume that it's not faster, and I am well aware that this is not what references are for. So I think my own guesses are quite good, I'm just looking for an answer from someone who really knows what's definitely happening under the hood. In five years of PHP development, I've always found it hard to get quality information on PHP internals short from reading the source.

9 Answers

The Zend Engine uses copy-on-write, 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 links.

(EDIT) The manual page on Objects and references contains a little more info on how object variables differ from references.

I'm pretty sure that no, it's not faster. Additionally, it says specifically in the manual not to try using references to increase performance.

Edit: Can't find where it says that, but it's there!

Is simple, there is no need to test anything. Depends on use-case.

Pass by value will ALWAYS BE FASTER BY VALUE than reference for small amount of arguments. This depends by how many variables that architecture allows to be passed through registers (ABI).

For example x64 will allow you 4 values 64 bit each to be passed through registers. https://en.wikipedia.org/wiki/X86_calling_conventions

This is because you don't have to de-referentiate the pointers, just use value directly.

If your data that needs to be passed is bigger than ABI, rest of values will go to stack. In this case, a array or a object (which in instance is a class, or a structure + headers) will ALWAYS BE FASTER BY REFERENCE.

This is because a reference is just a pointer to your data (not data itself), fixed size, say 32 or 64 bit depending on machine. That pointer will fit in one CPU register.

PHP is written in C/C++ so I'd expect to behave the same.

There is no need for adding & operator when passing objects. In PHP 5+ objects are passed by reference anyway.

Related