Some speed tests
<?php
$timer = function ($name = 'default', $unset_timer = TRUE)
{
static $timers = array();
if ( isset( $timers[ $name ] ) )
{
list($s_sec, $s_mic) = explode(' ', $timers[ $name ]);
list($e_sec, $e_mic) = explode(' ', microtime());
if ( $unset_timer )
unset( $timers[ $name ] );
return $e_sec - $s_sec + ( $e_mic - $s_mic );
}
$timers[ $name ] = microtime();
};
function f1 ($array) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ( $iterator as $key => $value ) {
if ( is_array($value) )
continue;
}
}
function f2($array) {
foreach ( $array as $key => $value ) {
if ( is_array($value) )
f2($value);
}
}
foreach ( [100, 1000, 10000, 100000, 1000000] as $num )
{
$array = [];
for ( $i = 0; ++$i < $num; )
$array[] = [1,2,3=>[4,5,6=>[7,8,9=>10,11,12=>[13,14,15=>[16,17,18]]]]];
$timer();
f1($array);
printf("RecursiveIteratorIterator: %7d elements -> %.3f sec\n", $num, $timer());
$timer();
f2($array);
printf("Recursive function : %7d elements -> %.3f sec\n", $num, $timer());
}
?>
Output (PHP 5.4.9-4ubuntu2.1 (cli) (built: Jun 11 2013 13:10:01))
=======================
RecursiveIteratorIterator: 100 elements -> 0.007 sec
Recursive function : 100 elements -> 0.002 sec
RecursiveIteratorIterator: 1000 elements -> 0.036 sec
Recursive function : 1000 elements -> 0.024 sec
RecursiveIteratorIterator: 10000 elements -> 0.425 sec
Recursive function : 10000 elements -> 0.263 sec
RecursiveIteratorIterator: 100000 elements -> 8.153 sec
Recursive function : 100000 elements -> 2.654 sec
RecursiveIteratorIterator: 1000000 elements -> 474.483 sec
Recursive function : 1000000 elements -> 26.872 sec
For one million elements recursive function is more quickly!