PHP 是否优化数组类型的函数参数,而不是在未修改时通过引用显式传递?

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

PHP 引擎会优化第二个示例以通过引用传递 $arr 吗?

function test1(array &$arr)
{
    $arr[] = 123;

    echo $arr[0];
}

function test2(array $arr)
{
    echo $arr[0];
}

PHP 使用一种称为 copy-on-write to avoid exactly the excessive copying of variables as long as it's unnecessary to do so. So even in your test2() example $array is not copied at all. If you'd modified $array inside the function, PHP would have copied the variable to allow modification. A detailed explanation of this mechanism can be found in the "Memory Management" chapter of the "PHP Internals Book". The following quote is from the "Reference-counting and copy-on-write" 部分的机制:

If you think about the above for a bit, you’ll come to the conclusion that PHP must be doing an awful 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 a double, but imagine passing an array with ten million elements to a function. Copying millions of elements on every call would be prohibitively slow.

To avoid doing so, PHP employs the copy-on-write paradigm: A zval can be shared by multiple variables/functions/etc as long as it’s only read from and not modified. If one of the holders wants to modify it, the zval needs to be copied before applying any changes.

以下两篇文章提供了对该主题的更多见解(均由 PHP 核心开发人员撰写):

第一个甚至解释了为什么仅出于性能原因使用引用通常不是一个好主意:

Another reason people use reference is since they think it makes the code faster. But this is wrong. It is even worse: References mostly make the code slower!

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

第二个显示了为什么对象在 PHP5+ 中没有真正通过引用传递。