在PHP(> = 5.0)中,通过引用传递速度更快吗? [英] In PHP (>= 5.0), is passing by reference faster?

查看:61
本文介绍了在PHP(> = 5.0)中,通过引用传递速度更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,可以通过在函数声明中的参数前面加上&"号来通过引用传递函数参数,如下所示:

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.

相反,PHP似乎使用写时复制来避免在对象被更改之前复制对象(也许还有数组).因此,对于不更改其参数的函数,其效果应与您通过引用传递它们的效果相同.

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:可以肯定的是,我认为它并不快,而且我很清楚这不是引用的目的.所以我想我自己的猜测很好,我是在寻找一个真正知道内幕下肯定正在发生什么的人的答案.在PHP开发的五年中,我总是发现很难通过阅读源代码来获得有关PHP内部构件的高质量信息.

推荐答案

Zend Engine使用写时复制,当您自己使用引用时,会产生一些额外的开销.只能找到此提及在撰写本文时,手册中的注释包含其他链接.

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.

这篇关于在PHP(> = 5.0)中,通过引用传递速度更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆