Alex Rivera | Logout

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

Asked 2008-10-07T13:04:40.800
78

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.

Edit
Report

3 Answers

31

I ran some test on this because I was unsure of the answers given.

My results show that passing large arrays or strings by reference IS significantly faster.

Here are my results: Benchmark

The Y axis (Runs) is how many times a function could be called in 1 second * 10

The test was repeated 8 times for each function/variable

And here is the variables I used:

$large_array = array_fill(PHP_INT_MAX / 2, 1000, 'a');
$small_array = array('this', 'is', 'a', 'small', 'array');
$large_object = (object)$large_array;
$large_string = str_repeat('a', 100000);
$small_string = 'this is a small string';
$value = PHP_INT_MAX / 2;

These are the functions:

function pass_by_ref(&$var) {
}

function pass_by_val($var) {
}
answered 2011-07-05T03:54:03.397
3

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!

answered 2008-10-07T13:06:58.317
-3

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

answered 2008-10-07T13:17:33.037

Your Answer