php array walk 效率,PHP中array_walk 和 foreach, for 的效率比较及性能优化

/**

* array_walk 和 foreach, for 的效率的比较。

* 我们要测试的是foreach, for, 和 array_walk的效率的问题。

*/

//产生一个10000的一个数组。

$max = 10000;

$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}\n";

$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}\n";

$t1 = microtime(true);

for ($i = 0; $i < $max; $i++) {

addOne($test_arr[$i]);

}

$t2 = microtime(true);

$t = $t2 - $t1;

echo "使用for 调用函数对数组操作 花费 : {$t}\n";

$t1 = microtime(true);

foreach ($test_arr as $k => &$v) {

$temp = $temp + 1;

}

$t2 = microtime(true);

$t = $t2 - $t1;

echo "使用 foreach 没有对数组操作 花费 : {$t}\n";

$t1 = microtime(true);

foreach ($test_arr as $k => &$v) {

$v = $v + 1;

}

$t2 = microtime(true);

$t = $t2 - $t1;

echo "使用 foreach 直接对数组操作 : {$t}\n";

$t1 = microtime(true);

foreach ($test_arr as $k => &$v) {

addOne($v);

}

$t2 = microtime(true);

$t = $t2 - $t1;

echo "使用 foreach 调用函数对数组操作 : {$t}\n";

$t1 = microtime(true);

array_walk($test_arr, 'addOne');

$t2 = microtime(true);

$t = $t2 - $t1;

echo "使用 array_walk 花费 : {$t}\n";

function addOne(&$item) {

$item = $item + 1;

}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值