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

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

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

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

$start = microtime(true);
for ($i=0; $i < 10000; $i++) { 
    $arr = test1($array);
    $arr[$i] = 'new';
}
$end = microtime(true);
echo "Cost ".($end - $start)."\n";

$start = microtime(true);
for ($i=0; $i < 10000; $i++) { 
    $arr = test2($array);
    $arr[$i] = 'new';
}
$end = microtime(true);
echo "Cost ".($end - $start)."\n";

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


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


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

【热门文章】
【热门文章】