嘿。今天我写了一个小的基准脚本来比较复制变量和创建对它们的引用的性能。我期待,例如,创建对大型数组的引用会比复制整个数组慢得多。这是我的基准代码:
<?php
$array = array();
for($i=0; $i<100000; $i++) {
$array[] = mt_rand();
}
function recursiveCopy($array, $count) {
if($count === 1000)
return;
$foo = $array;
recursiveCopy($array, $count+1);
}
function recursiveReference($array, $count) {
if($count === 1000)
return;
$foo = &$array;
recursiveReference($array, $count+1);
}
$time = microtime(1);
recursiveCopy($array, 0);
$copyTime = (microtime(1) - $time);
echo "Took " . $copyTime . "s \n";
$time = microtime(1);
recursiveReference($array, 0);
$referenceTime = (microtime(1) - $time);
echo "Took " . $referenceTime . "s \n";
echo "Reference / Copy: " . ($referenceTime / $copyTime);
我得到的实际结果是,recursiveReference 大约需要 recursiveCopy 的 20 倍(!)。
有人可以解释这种 PHP 行为吗?