for和foreach效率比较
$arr = array('rFG3','rShJ','pARu',.....); // 8000条数据1. for循环
$starttime = explode(' ',microtime());
for($i=0;$i<count($arr);$i++){
$i;
}
$endtime = explode(' ',microtime());
$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
echo "执行耗时:".$thistime." 秒。";
执行是输出:执行耗时:0.033001899719238 秒。
2. for count // 把count()函数提出来再执行for循环
$starttime = explode(' ',microtime());
$count = count($arr);
for($i=0;$i<$count;$i++){
$i;
}
$endtime = explode(' ',microtime());
$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
echo "执行耗时:".$thistime." 秒。";执行是输出:执行耗时:0.002000093460083 秒。对比两个执行的时间,可以很明确地看到2比1块了许多
所以在使用for循环并且需要count的时候,建议把count()写到变量再进行循环,这样速度会快好多
3.foreach
$starttime = explode(' ',microtime());
foreach ($arr as $k => $v){
$k;
}
$endtime = explode(' ',microtime());
$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);
echo "执行耗时:".$thistime." 秒。";执行是输出:执行耗时:0.00099992752075195 秒。对比2执行的时间,可以很明确地看到3比1块了许多
所以在进行数组遍历的时候建议使用foreach
本文探讨了在处理数组时,for循环与foreach循环的效率差异。建议在需要获取数组长度时,先将count()结果存储到变量再用for循环,以提高执行速度。对于数组遍历,推荐使用foreach循环。
539

被折叠的 条评论
为什么被折叠?



