@ 2018-09-16T10:49:29Z <?php
$input = [
'a',
['b', 'c'],
'd', ['e'], ['f', 'g'],
['h', 'i', ['j', ['k'], ['l', 'm', ['n']]]],
'o', 'p', ['q', 'r'], ['s', ['t', ['u', ['v']]]],
'w', 'x', 'y', 'z'];
class TraversableInput implements \IteratorAggregate
{
public $input = [
'a',
['b', 'c'],
'd', ['e'], ['f', 'g'],
['h', 'i', ['j', ['k'], ['l', 'm', ['n']]]],
'o', 'p', ['q', 'r'], ['s', ['t', ['u', ['v']]]],
'w', 'x', 'y', 'z'];
function getIterator()
{
return new ArrayIterator($this->input);
}
}
$input = new TraversableInput();
function flatten1($input) {
return \array_reduce(
$input,
function ($carry, $item) {
return \is_array($item) ?
\array_merge($carry, flatten1($item)) :
\array_merge($carry, [$item]);
},
[]
);
}
function flatten2($input) {
$stack = [$input];
$result = [];
while (!empty($stack)) {
$item = array_shift($stack);
if (is_array($item) || $item instanceof Traversable) {
foreach ($item as $element) {
array_unshift($stack, $element);
}
} else {
array_unshift($result, $item);
}
}
return $result;
}
$start = microtime(TRUE);
for($x=0;$x<10000;$x++){
flatten1($input);
};
$end = microtime(TRUE);
$diff = $end-$start;
$sec = intval($diff);
$micro = $diff - $sec;
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.10f', $micro));
echo "Flatten1: " . $final . "\n";
$start = microtime(TRUE);
for($x=0;$x<10000;$x++){
flatten2($input);
};
$end = microtime(TRUE);
$diff = $end-$start;
$sec = intval($diff);
$micro = $diff - $sec;
$final = strftime('%T', mktime(0, 0, $sec)) . str_replace('0.', '.', sprintf('%.10f', $micro));
echo "Flatten2: " . $final . "\n";
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Here you find the average performance (time & memory) of each version. A grayed out version indicates it didn't complete successfully (based on exit-code).
Version System time (s) User time (s) Memory (MiB) 7.2.10 0.108 0.007 14.38 7.2.9 0.093 0.009 14.76 7.2.8 0.106 0.010 14.53 7.2.7 0.120 0.013 14.89 7.2.6 0.102 0.013 14.95 7.2.5 0.079 0.009 14.73 7.2.4 0.090 0.013 14.95 7.2.3 0.118 0.003 14.95 7.2.2 0.081 0.014 14.89 7.2.1 0.140 0.009 14.93 7.2.0 0.079 0.000 15.13 7.1.22 0.088 0.015 13.75 7.1.21 0.084 0.003 13.83 7.1.20 0.064 0.016 13.75 7.1.19 0.078 0.007 13.67 7.1.18 0.131 0.010 13.84 7.1.17 0.121 0.003 13.73 7.1.16 0.103 0.007 14.02 7.1.15 0.111 0.007 13.73 7.1.14 0.071 0.009 13.61 7.1.13 0.215 0.003 13.86 7.1.12 0.096 0.009 13.93 7.1.11 0.066 0.007 13.83 7.1.10 0.077 0.010 13.89 7.1.9 0.102 0.007 13.70 7.1.8 0.110 0.012 13.76 7.1.7 0.077 0.000 13.84 7.1.6 0.116 0.007 31.85 7.1.5 0.111 0.016 31.83 7.1.4 0.084 0.013 31.98 7.1.3 0.139 0.019 31.73 7.1.2 0.158 0.003 31.79 7.1.1 0.121 0.003 13.66 7.1.0 0.114 0.013 13.87
preferences:dark mode live preview
27.09 ms | 403 KiB | 5 Q