@ 2018-09-16T11:59:38Z <?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(
(array) $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.3.1 0.020 0.302 16.61 7.3.0 0.013 0.301 16.73 7.2.13 0.026 0.319 16.89 7.2.12 0.037 0.342 16.77 7.2.11 0.017 0.308 16.82 7.2.10 0.140 0.312 15.51 7.2.9 0.203 0.329 15.82 7.2.8 0.158 0.329 15.73 7.2.7 0.143 0.312 16.16 7.2.6 0.138 0.315 16.06 7.2.5 0.158 0.331 15.79 7.2.4 0.192 0.358 15.72 7.2.3 0.183 0.376 15.85 7.2.2 0.215 0.362 15.72 7.2.1 0.200 0.383 15.60 7.2.0 0.182 0.317 16.08 7.1.25 0.010 0.481 15.48 7.1.22 0.420 0.485 13.87 7.1.21 0.319 0.402 13.84 7.1.20 0.250 0.360 13.61 7.1.19 0.310 0.331 13.66 7.1.18 0.273 0.340 13.97 7.1.17 0.394 0.489 13.77 7.1.16 0.383 0.484 13.74 7.1.15 0.351 0.390 14.04 7.1.14 0.321 0.446 13.80 7.1.13 0.363 0.441 13.52 7.1.12 0.338 0.541 13.88 7.1.11 0.377 0.497 13.82 7.1.10 0.338 0.486 14.16 7.1.9 0.470 0.409 13.95 7.1.8 0.411 0.401 13.89 7.1.7 0.429 0.394 13.64 7.1.6 0.439 0.446 31.96 7.1.5 0.653 0.431 31.99 7.1.4 0.659 0.425 31.40 7.1.3 0.635 0.439 32.01 7.1.2 0.715 0.473 31.80 7.1.1 0.586 0.526 13.70 7.1.0 0.387 0.351 13.99
preferences:dark mode live preview
28.87 ms | 403 KiB | 5 Q