PHP引用和性能

扫码查看

This question already has answers here:
In PHP (>= 5.0), is passing by reference faster?

(9个答案)


1年前关闭。




我阅读了一些有关PHP引用以及它们如何影响性能的文章。
我还看到了一些测试,证明了这一点。

这些资源中的大多数声称其原因是因为引用禁用了写时复制。

但是我不明白为什么会引起问题? PHP不会复制数组,例如,只是因为您通过引用传递了它。
function foo(&$var) {
    $var->test = 'bar';
    xdebug_debug_zval('var');
}

$data = new stdclass;
foo($data);

结果我收到了
(refcount=3, is_ref=1),
object(stdClass)[1]
public 'test' => (refcount=1, is_ref=0),string 'bar' (length=3)

这表明没有进行复制,并且该函数仍在使用相同的变量(处理实际变量而不是复制)。

我错过了什么,为什么会出现性能损失?

最佳答案

我尝试使用3v4l.com网站进行替补。
您可以在此处找到源:https://3v4l.org/NqHlZ
这是我针对最新的最新PHP版本(经过1万次迭代)得到的结果:
5.5.33的输出

Avergages:
    - Object through reference, explicitly: 2.5538682937622E-6
    - Object through reference, implicitly: 1.8869638442993E-6
    - Array through copy-on-write: 1.9102573394775E-6
    - Array through reference: 9.3061923980713E-7
5.6.19的输出
Avergages:
    - Object through reference, explicitly: 2.2409210205078E-6
    - Object through reference, implicitly: 1.7436265945435E-6
    - Array through copy-on-write: 1.1391639709473E-6
    - Array through reference: 8.7485313415527E-7
7.0.4的输出
Avergages:
    - Object through reference, explicitly: 4.6207904815674E-7
    - Object through reference, implicitly: 3.687858581543E-7
    - Array through copy-on-write: 4.0757656097412E-7
    - Array through reference: 3.0455589294434E-7
因此,对于所有最新的PHP版本,通过引用传递而不是写时复制都没有性能问题。
实际上,“通过引用实现对象”部分实际上不是一种编码方式,因为所有对象都通过引用传递,无论是否使用“&”符号。当变量是一个对象导致到达包含另一个包含数据的内存地址的内存地址时,也许使用此符号通过引用将变量显式传递给引用,这将解释为什么它需要更长的时间。

10-07 19:30
查看更多