Does PHP optimize array type function arguments not explicitly passed by reference when they are not changed?

Will the PHP engine optimize the second example for passing $arr by reference?

 function test1(array &$arr) { $arr[] = 123; echo $arr[0]; } function test2(array $arr) { echo $arr[0]; } 
+6
source share
1 answer

PHP uses the copy-on-write mechanism to avoid over-copying variables if it is not needed. Therefore, even in your test2() example, $array not copied at all. If you changed $array inside a function, PHP would copy this variable to allow its modification. A detailed explanation of this mechanism can be found in the Memory Management chapter of the PHP Internal Book . The following quote from the section "Link-counting and copying to record" :

If you think about it above, you will come to the conclusion that PHP should do a lot of copying. Every time you pass something to a function, the value needs to be copied. This may not be particularly problematic for an integer or double, but imagine passing an array with ten million elements to a function. copying millions of items with every call will be excessively slow.

To avoid this, PHP uses a copy-on-write paradigm: A zval can be shared by several variables / functions / etc., if only read and not changed. If one of the owners wants to change it, zval must be copied before applying any changes.

The following two articles provide a deeper understanding of this topic (both written by PHP developers):

The first one even explains why using links just for performance reasons is most often a bad idea:

Another reason people use the link is because they think it makes it faster. But it's not right. This is even worse: links basically make code slower!

Yes, links often make code slower - Sorry, I just had to repeat this to make it clear.

And the second one shows why objects are not passed by reference in PHP5 +.

+4
source

All Articles