天天看點

php的foreach,while,for的性能比較

<span style="color: rgb(54, 46, 43); font-family: Arial; font-size: 14px; line-height: 26px;">關注微信公衆号:wwwcoder,現在已将部落格搬到這裡,内容精選過後才釋出出來。謝謝大家支援</span>
           
for ($j = 10; $j > 0; $j--) {

    $itmes = array_fill(0, 100000, '12345678910');

    $start = microtime(true);
    reset($itmes);
    foreach ($itmes as $item) {
        $x = $item;
    }
    $end[] = microtime(true) - $start;
}
echo "<br>";
echo "foreach執行10次後的平均耗時:" . array_sum($end) / count($end) . "毫秒";
echo "<br>";

for ($j = 10; $j > 0; $j--) {

    $itmes = array_fill(0, 100000, '12345678910');

    $start = microtime(true);
    reset($itmes);
    $i = 0;
    while ($i < 100000) {
        $x = $itmes[$i];
        $i++;
    }
    $end1[] = microtime(true) - $start;
}
echo "<br>";
echo "while執行10次後的平均耗時:" . array_sum($end1) / count($end1) . "毫秒";
echo "<br>";

for ($j = 10; $j > 0; $j--) {

    $itmes = array_fill(0, 100000, '12345678910');

    $start = microtime(true);
    reset($itmes);
    for ($i = 0; $i < 100000; $i++) {
        $x = $itmes[$i];
    }
    $end2[] = microtime(true) - $start;
}
echo "<br>";
echo "for執行10次後的平均耗時:" . array_sum($end2) / count($end2) . "毫秒";
echo "<br>";
           

執行結果:

foreach執行10次後的平均耗時:0.023235964775085毫秒

while  執行10次後的平均耗時:0.043575739860535毫秒

for    執行10次後的平均耗時:0.04455361366272毫秒

有什麼不正确的地方請大家指出來,謝啦。