第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

for與foreach哪個(gè)更快?

for與foreach哪個(gè)更快?

精慕HU 2019-03-01 11:07:46
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更快了

查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
嗶嗶one

TA貢獻(xiàn)1854條經(jīng)驗(yàn) 獲得超8個(gè)贊

遍歷數(shù)組還是用foreach吧,畢竟不用先統(tǒng)計(jì)數(shù)組。

查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
慕碼人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 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.

他提到這個(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...
查看完整回答
反對(duì) 回復(fù) 2019-03-01
  • 4 回答
  • 0 關(guān)注
  • 998 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)