昨日晚上,在不经意间听到别人说php中for循环效率比foreach高,尽量多用for循环可以提高php效率。
听到这个论调,我当时一愣,for每次循环前都要进行判断,而foreach只需在数组内部移动指针,for的效率会比foreach要高?
-------------------
今天特地写了个简单的脚本做了测试(以下结果皆采用多次测试后的平均值)$max = 100000;
$arr = range(0,$max);
$t1 = microtime(true);
for($i = 0;$i
$temp = $arr[$i] + 1;
}
$t2 = microtime(true);
$for_t = $t2-$t1;
echo "for 循环:".$for_t."
";
$t1 = microtime(true);
foreach($arr as $v){
$temp = $v + 1;
}
$t2 = microtime(true);
$foreach_t = $t2-$t1;
echo "foreach 循环:".$foreach_t."
";
echo "foreach 循环与 for 循环用时差为:".($for_t - $foreach_t)."
";
结果:
for 循环:0.0095438957214