標籤:php 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
array_walk 和 foreach, for 的效率的比較