array_walk 和 foreach, for 的效率的比較

來源:互聯網
上載者:User

標籤: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 的效率的比較

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.