Home  >  Article  >  Backend Development  >  Comparison of the efficiency of array_walk and foreach, for

Comparison of the efficiency of array_walk and foreach, for

WBOY
WBOYOriginal
2016-08-08 09:31:421934browse

Use the mini program to judge the efficiency of array_walk and foreach, and find the following results through the mini program:

1. The efficiency of foreach is significantly higher than for, indicating that PHP has optimized the foreach function. If colleagues can use for and foreach Where, it is recommended to use foreach.

2. If you want to call a function in the loop, it is best to use array_walk.

<?php
/**
 * array_walk 和 foreach, for 的效率的比较。
 * 我们要测试的是foreach, for, 和 array_walk的效率的问题。 
 */

//产生一个10000的一个数组。
$max = 1000000;
$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;
}
?>
result:

Just use for, no cost for array operations: 0.348432064056
Use for and directly operate the array, cost: 0.493929862976
Use for Cost of calling a function to operate on the array: 1.49323606491
Using foreach without operating on the array: 0.33071398735
Using foreach to operate on the array directly: 0.337166070938
Using foreach to operate on the array: 1.13249397278
Cost of using array_walk: 1.2829349041

The above introduces the comparison of the efficiency of array_walk and foreach, for, including aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn