for與foreach哪個(gè)性能更好一些?還是處理不同的數(shù)據(jù)有各自的優(yōu)點(diǎn)?希望大神給解答一下.
4 回答

慕標(biāo)5832272
TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
foreach
特別是php7 修改了array的數(shù)據(jù)結(jié)構(gòu)后 foreach更快了

慕碼人8056858
TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
這類(lèi)問(wèn)題,應(yīng)該StackOverflow上也有了:Performance of FOR vs FOREACH in PHP
得票最高的作者說(shuō):“他幾乎很少用for”,不過(guò)這兩者的區(qū)別在大多數(shù)情況下都是很小的。
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.
他提到這個(gè)循環(huán)(比較差的寫(xiě)法):
for ($i = 0; $i < count($array); $i++) {
是一個(gè)很昂貴的循環(huán),因?yàn)槊看味家{(diào)用count(感覺(jué)這種寫(xiě)法大家都是避免的)
他還貼了一個(gè)對(duì)比測(cè)試: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...
添加回答
舉報(bào)
0/150
提交
取消