array_walk 和 foreach, for 的效率的比較

通過小程序,判斷array_walk 和 foreach, for的效率,通過小程序發現如下結果:

1、foreach的效率明顯高於for,說明php對foreach函數進行了優化,如果同事可以採用for和foreach的地方,建議採用foreach。

2、如果循環內要調用函數,用array_walk  最好.

<?php
/**
 * array_walk 和 foreach, for 的效率的比較。
 * 我們要測試的是foreach, for, 和 array_walk的效率的問題。 
 */

//產生一個10000的一個數組。
$max = 1000000;
$test_arr = range(0, $max);
$temp;
//我們分別用三種方法測試求這些數加上1的值的時間。

// for 的方法
$t1 = microtime(true);
for ($i = 0; $i < $max; $i++) {
    $temp = $temp + 1;
}
$t2 = microtime(true);
$t = $t2 - $t1;
echo "就使用for, 沒有對數組操作 花費: {$t}\n";

$t1 = microtime(true);
for ($i = 0; $i < $max; $i++) {
    $test_arr[$i] = $test_arr[$i] + 1;
}
$t2 = microtime(true);
$t = $t2 - $t1;
echo "使用for 並且直接對數組進行了操作 花費: {$t}\n";

$t1 = microtime(true);
for ($i = 0; $i < $max; $i++) {
    addOne($test_arr[$i]);
}
$t2 = microtime(true);
$t = $t2 - $t1;
echo "使用for 調用函數對數組操作 花費 : {$t}\n";

$t1 = microtime(true);
foreach ($test_arr as $k => &$v) {
    $temp = $temp + 1;
}
$t2 = microtime(true);
$t = $t2 - $t1;
echo "使用 foreach 沒有對數組操作 花費 : {$t}\n";

$t1 = microtime(true);
foreach ($test_arr as $k => &$v) {
    $v = $v + 1;
}
$t2 = microtime(true);
$t = $t2 - $t1;
echo "使用 foreach 直接對數組操作 : {$t}\n";

$t1 = microtime(true);
foreach ($test_arr as $k => &$v) {
    addOne($v);
}
$t2 = microtime(true);
$t = $t2 - $t1;
echo "使用 foreach 調用函數對數組操作 : {$t}\n";

$t1 = microtime(true);
array_walk($test_arr, 'addOne');
$t2 = microtime(true);
$t = $t2 - $t1;
echo "使用 array_walk 花費 : {$t}\n";

function addOne(&$item) {
    $item = $item + 1;
}
?>
結果:

就使用for, 沒有對數組操作 花費: 0.348432064056
使用for 並且直接對數組進行了操作 花費: 0.493929862976
使用for 調用函數對數組操作 花費 : 1.49323606491
使用 foreach 沒有對數組操作 花費 : 0.33071398735
使用 foreach 直接對數組操作 : 0.337166070938
使用 foreach 調用函數對數組操作 : 1.13249397278
使用 array_walk 花費 : 1.2829349041

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章