for與foreach哪個性能更好一些?還是處理不同的數據有各自的優點?希望大神給解答一下.
4 回答

慕碼人8056858
TA貢獻1803條經驗 獲得超6個贊
這類問題,應該StackOverflow上也有了:Performance of FOR vs FOREACH in PHP
得票最高的作者說:“他幾乎很少用for”,不過這兩者的區別在大多數情況下都是很小的。
My personal opinion is to use what makes sense in the context. Personally I almost never usefor
for array traversal. I use it for other types of iteration, butforeach
is just too easy... The time difference is going to be minimal in most cases.
他提到這個循環(比較差的寫法):
for ($i = 0; $i < count($array); $i++) {
是一個很昂貴的循環,因為每次都要調用count(感覺這種寫法大家都是避免的)
他還貼了一個對比測試:for foreach foreach中用引用
$a = array();
for ($i = 0; $i < 10000; $i++) {
$a[] = $i;
}
$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";
And the results:
Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds
So if you're modifying the array in the loop, it's several times faster to use references...
添加回答
舉報
0/150
提交
取消