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

查看:30
本文介绍了在 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.

但是,我想知道 Copy On Write 逻辑是否可能在传递引用时短路,以及这是否会影响性能.

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 引擎使用写时复制,当您自己使用引用时,会产生一些额外的开销.只能找到这个提及 在撰写本文时,手册中的评论包含其他链接.

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天全站免登陆