When can array_walk and foreach traverse arrays be more efficient?

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.