php中for循环与foreach循环效率比较
昨日晚上,在不经意间听到别人说php中for循环效率比foreach高,尽量多用for循环可以提高php效率。
成都创新互联公司主要从事成都网站建设、成都网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务姜堰,10年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18982081108
听到这个论调,我当时一愣,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."
"; $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.00954389572144
foreach 循环:0.00662207603455
foreach 循环与 for 循环用时差为:0.00292181968689
---------
这么看似乎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."
"; $t1 = microtime(true); foreach($arr as $k => $v){ $arr[$k] = $v + 1; } $t2 = microtime(true); $foreach_t = $t2-$t1; echo "foreach 循环:".$foreach_t."
"; echo "foreach 循环与 for 循环用时差为:".($for_t - $foreach_t)."
";
结果:
for 循环:0.0129821300507
foreach 循环:0.0405921936035
foreach 循环与 for 循环用时差为:-0.0276100635529
---
对本身数组进行直接操作发现,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."
"; $t1 = microtime(true); foreach($arr as $k => $v){ $arr[$i] = $v + 1; } $t2 = microtime(true); $foreach_t = $t2-$t1; echo "foreach 循环:".$foreach_t."
"; echo "foreach 循环与 for 循环用时差为:".($for_t - $foreach_t)."
";
结果:
for 循环:0.0401809215546
foreach 循环:0.0275750160217
foreach 循环与 for 循环用时差为:0.0126059055328
-----
foreach要比for高出32%
-----------------------------------------------------------------------
结论:
1.大多数情况下,foreach的效率都要比for高。
2.在数组的键名为连续数字时,for要比foreach效率高。
当前名称:php中for循环与foreach循环效率比较
当前路径:http://myzitong.com/article/godcph.html