我们来测试一下for foreach array_map 这三个遍历数组方式的性能
测试环境
操作系统:Windows 7 64 位
PHP版本:5.3.8 x64 TS
开始测试
for 循环
测试代码
$array = range(1, 1000);
$start_time = microtime(true);
$length = count($array);
for($i=0; $i < 1000; $i++)
{
for($j=0; $j < $length; $j++)
{
// do something
}
}
$end_time = microtime(true);
echo ($end_time-$start_time)*10000;
测试结果为:1147.5515365601
-
foreach 不使用键
$array = range(1, 1000);
$start_time = microtime(true);
$length = count($array);
for($i=0; $i < 1000; $i++)
{
foreach($array as $value)
{
// do something
}
}
$end_time = microtime(true);
echo ($end_time-$start_time)*10000;
测试结果:452.22043991089
-
foreach 使用键
$array = range(1, 1000);
$start_time = microtime(true);
$length = count($array);
for($i=0; $i < 1000; $i++)
{
foreach($array as $key=>$value)
{
// do something
}
}
$end_time = microtime(true);
echo ($end_time-$start_time)*10000;
测试结果:945.38927078247
-
array_map
$array = range(1, 1000);
$start_time = microtime(true);
$length = count($array);
for($i=0; $i < 1000; $i++)
{
array_map(function($el){
// do something
}, $array);
}
$end_time = microtime(true);
echo ($end_time-$start_time)*10000;
测试结果:7564.5303726196
总结
测试方法 | 测试次数 | 耗时 |
---|---|---|
for循环 | 1 | 1147.5515365601 |
foreach 不使用键 | 1 | 452.22043991089 |
foreach 使用键 | 1 | 945.38927078247 |
array_map | 1 | 7564.5303726196 |
查看效率速度发现很明显 是foreach更快,这是为什么呢,foreach比for循环快的原因是因为foreach内部用链表存储,所以移动起来更快,而array_map array_walk显然封装过扩展,没有底层快的。当不使用key的时候 foreach要快一倍,也就告诉我们今后用数组如果不需要用到key的时候尽量不写 $key=> 来提高效率。
最后:还是看实际情况使用吧!
评论 (0)