效率对比

可以选用array_walk array_map foreach for

产生数组

1
2
$max = 100000;
$arr = range(0, $max);

for

0.020256996154785
0.019799947738647
0.020244121551514[

1
2
3
4
5
6
7
8
// for
$temp = 0;
$t1 = microtime(true);
for ($i = 0; $i < $max; $i++)
{
callback($arr[$i]);
}
$t2 = microtime(true);

foreach

0.017144918441772
0.017565965652466
0.02012300491333

1
2
3
4
5
6
7
$temp=0;
$t1 = microtime(true);
foreach ($arr as $value) {
callback($value);
}
$t2 = microtime(true);
echo $t2 - $t1;

array_walk

0.02513313293457
0.024876832962036
0.026274919509888

1
2
3
4
5
6
7
$temp=0;
$t1 = microtime(true);
array_walk($arr,function() use($temp){
$temp++;
});
$t2 = microtime(true);
echo $t2 - $t1;

array_map

0.026141166687012
0.027121782302856
0.021435022354126

1
2
3
4
5
6
7
8
9
$temp=0;
$t1 = microtime(true);
array_map('callback',$arr);
$t2 = microtime(true);
echo $t2 - $t1;
function callback($value){
global $temp;
$temp++;
}

测试结论

网上有很多号称array_map比较快,经过实测发现实际结果是
foreach = for > array_walk = array_map
当然性能相差太小了
10000个循环才这点差距,我也不想说啥了