array_walk比foreach快?实际操作对比

<?php

function getmicrotime()
{
list($usec, $sec) = explode(” “,microtime());
return ((float)$usec + (float)$sec);
}
//
//
//
$time_start = getmicrotime();
$array = [];
for($i=0;$i<100000;$i++){
$array[] = $i;
}
echo ‘数据量:’.count($array);
echo “\n”;
$str = implode($array,’,’);
//// 记录结束时间
$aaa = 1;
$time_start1 = getmicrotime();
//test code
array_walk($array, function($aaa){
return $aaa++;
});

$time_end1 = getmicrotime();
echo ‘array_walk用时:’.sprintf(“%.8f”, $time_end1-$time_start1);
//////////////////////
echo “\n”;
$time_start2 = getmicrotime();
//test code
foreach($array as $k => $v) {
$aaa ++;
}
$time_end2 = getmicrotime();
echo ‘foreach用时:’.sprintf(“%.8f”, $time_end2-$time_start2);
?>

实际操作结果

环境php版本:  PHP7

十万数据循环

WX20171020-134933@2x

显示操作运行时间    foreach 是array_walk 的三分之一左右

上面附测试代码

发表评论

电子邮件地址不会被公开。 必填项已用*标注