入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

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

创建时间:2016-08-18 投稿人: 浏览次数:979
<?php
header("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


声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。