<pre name="code" class="php"><?php
/**
* for foreach array_reduce 执行效率比较:
* 综合下来 foreach 最快 for 次之 array_reduce 最慢(相差一个小数点,但是代码写起来很有水平,一行代码搞定)
*/
$a=[1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,
7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,10,1,2,3,4,5,6,7,8,9,10,
3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,
7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,10,1,2,3,4,5,6,7,8,9,10,
3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,
7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,10,1,2,3,4,5,6,7,8,9,10,
3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,
1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,
7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,10,1,2,3,4,5,6,7,8,9,10,
3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,
];
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
//显得很有水平,其实数度最慢
array_reduce($a,function($v1,$v2){$v1 += $v2;return $v1;});
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "array_reduce spent $time seconds\n";
echo "<hr>";
$time_start = microtime_float();
$count = 0;
foreach($a as $val){
$count += $val;
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "foreach spent $time seconds\n";
echo "<hr>";
$time_start = microtime_float();
$count = 0;
$num = count($a);
for($i=0;$i<$num;$i++){
$count += $val;
}
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "for $time seconds\n";
php array
最新推荐文章于 2021-03-31 18:58:34 发布