Home  >  Article  >  Backend Development  >  函数返回引用为什么会比返回值慢呢?写时拷贝为什么会比引用慢呢?

函数返回引用为什么会比返回值慢呢?写时拷贝为什么会比引用慢呢?

WBOY
WBOYOriginal
2016-06-06 20:14:581192browse

<code>$array = range(1, 10000);
function test1($array)
{
    return $array;
}

function &test2($array)
{
    return $array;
}

$start = microtime(true);
for ($i=0; $i </code>

输出结果:
Cost 5.5163149833679
Cost 6.3323628902435
虽然差距不大

回复内容:

<code>$array = range(1, 10000);
function test1($array)
{
    return $array;
}

function &test2($array)
{
    return $array;
}

$start = microtime(true);
for ($i=0; $i </code>

输出结果:
Cost 5.5163149833679
Cost 6.3323628902435
虽然差距不大

拷贝需要开辟空间初始化之类的,相当于创建几个新的对象。
而引用只是一个指针。

首先、根据 PHP: 引用返回 - Manual 的解释,以上两种写法并没有什么区别,你可以理解没有加 & 的那个函数底层引擎是会优化的,所以可能确实快了一点点,所以手册上也是不推荐的。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn