PHP has array_walk() which can be used to traverse an array and modify it in place. I wanted to find out if array_walk() would be faster than a loop written in PHP (for, foreach). I mean, PHP’s code is written in C/C++ and traversing anything has to be faster in C than in PHP.
So, I wrote a script to traverse an array of about 100,000 elements. Below are the results (formatted for better readability):
new-host-2:exp moz$ php for.php
Method Time taken to traverse 100,000 elements
========================================================
for 0.030004024505615
foreach 0.0066280364990234
array_walk 0.019280910491943
new-host-2:exp moz$ php for.php
Method Time taken to traverse 100,000 elements
========================================================
for 0.041378974914551
foreach 0.0075538158416748
array_walk 0.02002215385437
new-host-2:exp moz$ php for.php
Method Time taken to traverse 100,000 elements
========================================================
for 0.029618978500366
foreach 0.0064899921417236
array_walk 0.018718957901001
new-host-2:exp moz$ php for.php
Method Time taken to traverse 100,000 elements
========================================================
for 0.041105985641479
foreach 0.007500171661377
array_walk 0.020205974578857
foreach traverses an associative array faster than array_walk() and for loop. In fact, it was much faster than both. I had expected array_walk to be faster but I was wrong. You will notice that the while loop isnt in there. I figured that a while loop would take about the same time as a for loop. Here is the script I ran for my experiment:
$val) {
$tmp = $val;
}
Timer::stop();
Timer::diff('foreach');
Timer::start();
array_walk($assocArray, function ($item, $key) {
$tmp = $item;
});
Timer::stop();
Timer::diff('array_walk');
class Timer
{
protected static $start;
protected static $stop;
public static function start()
{
self::$start = microtime(true);
}
public static function stop()
{
self::$stop = microtime(true);
}
public static function diff($label)
{
print $label . "\t\t" . (self::$stop - self::$start) . PHP_EOL;
}
}
Leave a Reply