PHP: array_walk vs foreach

Its a minor optimization but might make a difference if you process large arrays. Built-in PHP function array_walk allows you to apply a function to every element in an array. Obviously you can get the same results using a foreach. One would expect the built-in function to be faster since its written in C and hopefully has been highly optimized but it turns out, that’s not the case. After a bit of online research and some tests, foreach is the clear winner. Here’s the examples:

[pastacode lang=”php” message=”Using foreach – 0.01022s” highlight=”” provider=”manual”]

<?php
$test = array_fill(0, 10000, 'test_data');
$start = microtime(true);

foreach ($test as $key => $value)
{
    $result[$key] = 'testdata';
}

$end = microtime(true);
$time = $end - $start;
printf( "%0.5fs", $time );

[/pastacode]

[pastacode lang=”php” message=”Using array_walk – 0.08700s” highlight=”” provider=”manual”]

<?php
$test = array_fill(0, 10000, 'test_data');
$start = microtime(true);

array_walk($test, function($value, $index)
{
    $value = 'testdata';
});

$end = microtime(true);
$time = $end - $start;
printf( "%0.5fs", $time );

[/pastacode]

foreach wins. Case closed.

Comments

comments