When can array_walk and foreach traverse arrays be more efficient? At last, this post was edited by lytreo650 from 2014-05-0616: 10: 08. a blog on the internet compares for, foreach, and array_walk, as mentioned above, if calling the arrar_walk function is more efficient, but when can I write a test script, array_walk and foreach, traverse the array?
This post was last edited by lytreo650 at 16:10:08 on
There is a blog on the Internet that compares for, foreach, and array_walk. as mentioned above, if calling the arrar_walk function is more efficient, I wrote a test script myself, foreach is faster than array_walk, isn't it because the function is too simple? Under what circumstances will array_walk be more efficient? When should I use array_walk?
$test = array();
for($i = 0; $i<10000; $i++) {
$test[$i] = $i;
}
function add($arg) {
return $arg++;
}
$one_time = microtime();
foreach($test as $key => $value) {
add($value);
}
$two_time = microtime();
array_walk($test, function ($value) {
return $value++;
});
$three_time = microtime();
$foreach_time = $two_time - $one_time;
$array_walk_time = $three_time - $two_time;
echo 'array_walk_time:=' . $array_walk_time . '
';
echo 'foreach_time:=' . $foreach_time;
------ Solution --------------------
Some people have been saying since php4
Array_walk is better than foreach than
Some examples can also be used to illustrate
But at least php5.4.20 overturned this conclusion.
You can use the same example to prove
For is better than foreach than array_walk
In this way, the facts will return to the original
Test example
Http://www.cnblogs.com/niniwzw/archive/2008/06/03/1212535.html
Http://www.nowamagic.net/academy/detail/1204408