入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

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

创建时间:2013-07-03 投稿人: 浏览次数:1570
<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毫秒
有什么不正确的地方请大家指出来,谢啦。

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。