PHP 中 FOR 和 FOREACH 的效能
與 “for” 迴圈相比,“foreach” 很慢。“foreach” 會複製需要執行迭代的陣列。
為了提高效能,需要使用引用概念。此外,‘foreach’ 易於使用。
示例
下面是一個簡單的程式碼示例 ——
<?php $my_arr = array(); for ($i = 0; $i < 10000; $i++) { $my_arr[] = $i; } $start = microtime(true); foreach ($my_arr as $k => $v) { $my_arr[$k] = $v + 1; } echo "This completed in ", microtime(true) - $start, " seconds"; echo "<br>"; $start = microtime(true); foreach ($my_arr as $k => &$v) { $v = $v + 1; } echo "This completed in ", microtime(true) - $start, " seconds"; echo "<br>"; $start = microtime(true); foreach ($my_arr as $k => $v) {} echo "This completed in ", microtime(true) - $start, " seconds"; echo "<br>"; $start = microtime(true); foreach ($my_arr as $k => &$v) {} echo "This completed in ", microtime(true) - $start, " seconds"; ?>
輸出
這將產生以下輸出 ——
This completed in 0.00058293342590332 seconds This completed in 0.00063300132751465 seconds This completed in 0.00023412704467773 seconds This completed in 0.00026583671569824 seconds
廣告