亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

for與foreach哪個更快?

for與foreach哪個更快?

精慕HU 2019-03-01 11:07:46
for與foreach哪個性能更好一些?還是處理不同的數據有各自的優點?希望大神給解答一下.
查看完整描述

4 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

foreach
特別是php7 修改了array的數據結構后 foreach更快了

查看完整回答
反對 回復 2019-03-01
?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

遍歷數組還是用foreach吧,畢竟不用先統計數組。

查看完整回答
反對 回復 2019-03-01
?
慕碼人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 use for for array traversal. I use it for other types of iteration, but foreach 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...
查看完整回答
反對 回復 2019-03-01
  • 4 回答
  • 0 關注
  • 994 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號