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