0
我做了一個小實驗,並得到了一個令人驚訝的結果(至少對我來說)。我已經寫了6個函數來以不同的方式在PHP中總結一個數組。在這裏你可以看到的結果:PHP如何使用通過ref或value傳遞的參數?
PHP ver: 5.5.36
foreach_by_value(): 1.1668000221252
foreach_by_ref(): 0.38018989562988
array_sum_by_value(): 0.11428999900818
array_sum_by_ref(): 0.91070008277893
for_by_value(): 0.50360298156738
for_by_ref(): 1.2752962112427
正如你所看到的,通過引用傳遞數組有時使得快於其他情況下慢。 不知道背後的原因是什麼。
這裏是我用於測試的代碼:
echo phpversion() . "\n";
const N = 100000;
const REPEAT = 100;
for ($i = 0;$i < N;$i++) {
$array[] = rand(0, 10000);
}
function foreach_by_value($a) {
$sum = 0;
foreach($a as $number) {
$sum += $number;
}
}
function foreach_by_ref(&$a) {
$sum = 0;
foreach($a as $number) {
$sum += $number;
}
}
function array_sum_by_value($a) {
$sum = array_sum($a);
}
function array_sum_by_ref(&$a) {
$sum = array_sum($a);
}
function for_by_value($array) {
$sum = 0;
$count = count($array);
for($i = 0;$i < $count;$i++) {
$sum += $array[$i];
}
}
function for_by_ref(&$array) {
$sum = 0;
$count = count($array);
for($i = 0;$i < $count;$i++) {
$sum += $array[$i];
}
}
$start_time = microtime(true);
for ($i = 0;$i < REPEAT;$i++) {
foreach_by_value($array);
}
$finish_time = microtime(true);
echo "foreach_by_value(): \t" . ($finish_time - $start_time) . "\n";
$start_time = microtime(true);
for ($i = 0;$i < REPEAT;$i++) {
foreach_by_ref($array);
}
$finish_time = microtime(true);
echo "foreach_by_ref(): \t" . ($finish_time - $start_time) . "\n";
$start_time = microtime(true);
for ($i = 0;$i < REPEAT;$i++) {
array_sum_by_value($array);
}
$finish_time = microtime(true);
echo "array_sum_by_value(): \t" . ($finish_time - $start_time) . "\n";
$start_time = microtime(true);
for ($i = 0;$i < REPEAT;$i++) {
array_sum_by_ref($array);
}
$finish_time = microtime(true);
echo "array_sum_by_ref(): \t" . ($finish_time - $start_time) . "\n";
$start_time = microtime(true);
for ($i = 0;$i < REPEAT;$i++) {
for_by_value($array);
}
$finish_time = microtime(true);
echo "for_by_value(): \t" . ($finish_time - $start_time) . "\n";
$start_time = microtime(true);
for ($i = 0;$i < REPEAT;$i++) {
for_by_ref($array);
}
$finish_time = microtime(true);
echo "for_by_ref(): \t\t" . ($finish_time - $start_time) . "\n";