php array_map array_walk for foreach效率比较 phpstudy apache php5.5 windows7旗舰版

来源:互联网 发布:javlib最新域名 2016 编辑:程序博客网 时间:2024/06/05 16:06
<?phpheader("Content-Type: text/html;charset=utf-8");/** * array_walk 和 foreach, for 的效率的比较。 * 我们要测试的是foreach, for, 和 array_walk的效率的问题。 *///产生一个10000的一个数组。$max = 100000;$test_arr = range(0, $max);$temp = '';//我们分别用三种方法测试求这些数加上1的值的时间。// for 的方法$t1 = microtime(true);for ($i = 0; $i < $max; $i++) {    $temp = $temp + 1;}$t2 = microtime(true);$t = $t2 - $t1;echo "就使用for, 没有对数组操作 花费: {$t}<br>";$t1 = microtime(true);for ($i = 0; $i < $max; $i++) {    $test_arr[$i] = $test_arr[$i] + 1;}$t2 = microtime(true);$t = $t2 - $t1;echo "使用for 并且直接对数组进行了操作 花费: {$t}<br>";$t1 = microtime(true);for ($i = 0; $i < $max; $i++) {    addOne($test_arr[$i]);}$t2 = microtime(true);$t = $t2 - $t1;echo "使用for 调用函数对数组操作 花费 : {$t}<br>";$t1 = microtime(true);foreach ($test_arr as $k => &$v) {    $temp = $temp + 1;}$t2 = microtime(true);$t = $t2 - $t1;echo "使用 foreach 没有对数组操作 花费 : {$t}<br>";$t1 = microtime(true);foreach ($test_arr as $k => &$v) {    $v = $v + 1;}$t2 = microtime(true);$t = $t2 - $t1;echo "使用 foreach 直接对数组操作 : {$t}<br>";$t1 = microtime(true);foreach ($test_arr as $k => &$v) {    addOne($v);}$t2 = microtime(true);$t = $t2 - $t1;echo "使用 foreach 调用函数对数组操作 : {$t}<br>";$t1 = microtime(true);array_walk($test_arr, 'addOne');$t2 = microtime(true);$t = $t2 - $t1;echo "使用 array_walk 花费 : {$t}<br>";$t1 = microtime(true);array_map('addOne', $test_arr);$t2 = microtime(true);$t = $t2 - $t1;echo "使用 array_map 花费 : {$t}<br>";function addOne(&$item) {    $item = $item + 1;}

就使用for, 没有对数组操作 花费: 0.005000114440918
使用for 并且直接对数组进行了操作 花费: 0.0079998970031738
使用for 调用函数对数组操作 花费 : 0.015001058578491
使用 foreach 没有对数组操作 花费 : 0.0070009231567383
使用 foreach 直接对数组操作 : 0.0060000419616699
使用 foreach 调用函数对数组操作 : 0.013000965118408
使用 array_walk 花费 : 0.020001173019409
使用 array_map 花费 : 0.053002834320068


0 0
原创粉丝点击