昨日晚上,在不经意间听到别人说php中for循环效率比foreach高,尽量多用for循环可以提高php效率。
听到这个论调,我当时一愣,for每次循环前都要进行判断,而foreach只需在数组内部移动指针,for的效率会比foreach要高?
-------------------
今天特地写了个简单的脚本做了测试(以下结果皆采用多次测试后的平均值)
$max = 100000;
$arr = range(0,$max);
$t1 = microtime(true);
for($i = 0;$i<$max; $i ++){
$temp = $arr[$i] + 1;
}
$t2 = microtime(true);
$for_t = $t2-$t1;
echo "for 循环:".$for_t."<br>";
$t1 = microtime(true);
foreach($arr as $v){
$temp = $v + 1;
}
$t2 = microtime(true);
$foreach_t = $t2-$t1;
echo "foreach 循环:".$foreach_t."<br>";
echo "foreach 循环与 for 循环用时差为:".($for_t - $foreach_t)."<br>";
结果:
---------
这么看似乎foreach要比for效率高出30%
----------------------
那么在看如果对数组本身进行操作
$max = 100000;
$arr = range(0,$max);
$t1 = microtime(true);
for($i = 0;$i<$max; $i ++){
$arr[$i] = $arr[$i] + 1;
}
$t2 = microtime(true);
$for_t = $t2-$t1;
echo "for 循环:".$for_t."<br>";
$t1 = microtime(true);
foreach($arr as $k => $v){
$arr[$k] = $v + 1;
}
$t2 = microtime(true);
$foreach_t = $t2-$t1;
echo "foreach 循环:".$foreach_t."<br>";
echo "foreach 循环与 for 循环用时差为:".($for_t - $foreach_t)."<br>";
结果:
---
对本身数组进行直接操作发现,for要比foreach高出68%
但是我们可以看出在上面这个例子foreach支持对复杂键名的操作,而for只能操作键名为从0起的连续数字的数组。
--------------
为了公平起见,在看下面这个例子,将for循环改为同样可以操作复杂键名
$max = 100000;
$arr = range(0,$max);
$t1 = microtime(true);
$keys = array_keys($arr);
for($i = 0;$i<$max; $i ++){
$arr[$keys[$i]] = $arr[$keys[$i]] + 1;
}
$t2 = microtime(true);
$for_t = $t2-$t1;
echo "for 循环:".$for_t."<br>";
$t1 = microtime(true);
foreach($arr as $k => $v){
$arr[$i] = $v + 1;
}
$t2 = microtime(true);
$foreach_t = $t2-$t1;
echo "foreach 循环:".$foreach_t."<br>";
echo "foreach 循环与 for 循环用时差为:".($for_t - $foreach_t)."<br>";
结果:
for 循环:0.0401809215546
foreach 循环:0.0275750160217
foreach 循环与 for 循环用时差为:0.0126059055328
-----
foreach要比for高出32%
-----------------------------------------------------------------------
结论:
1.大多数情况下,foreach的效率都要比for高。
2.在数组的键名为连续数字时,for要比foreach效率高。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。