Created
May 11, 2018 13:56
-
-
Save KVytyagov/895dc063ad7126ecb967f8503c47ae0c to your computer and use it in GitHub Desktop.
Performance test array_merge vs array_push in loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
$arraysCount = 100; | |
$itemsInArray = 100; | |
$dataToMerge = []; | |
for ($i = 0; $i < $arraysCount; ++$i) { | |
for ($j = 0; $j < $itemsInArray; ++$j) { | |
$dataToMerge[$i][] = uniqid('', true); | |
} | |
} | |
$iterations = 500; | |
$results = []; | |
$memoryUsage = []; | |
for ($i = 0; $i < $iterations; ++$i) { | |
$start = \microtime(true); | |
$toMerge = [[]]; | |
foreach ($dataToMerge as $arr) { | |
$toMerge[] = $arr; | |
} | |
$out = \array_merge(...$toMerge); | |
$time = \microtime(true) - $start; | |
$name = 'Merge'; | |
$results[$name][] = $time; | |
$memoryUsage[$name] = memory_get_peak_usage(true); | |
} | |
for ($i = 0; $i < $iterations; ++$i) { | |
$start = \microtime(true); | |
$out = []; | |
foreach ($dataToMerge as $arr) { | |
array_push($out, ...$arr); | |
} | |
$time = \microtime(true) - $start; | |
$name = 'ArrayPush'; | |
$results[$name][] = $time; | |
$memoryUsage[$name] = memory_get_peak_usage(true); | |
} | |
echo 'Array count: ' . $arraysCount . '; items in array: ' . $itemsInArray . '; iterations: ' . $iterations . "\n"; | |
$calcResults = []; | |
foreach ($results as $test => $times) { | |
echo $test . "\n" . \implode("\t", [ | |
'[avg]: ' . \array_sum($times) / \count($times), | |
'[min]: ' . \min($times), | |
'[max]: ' . \max($times), | |
'[mem_usage]: ' . $memoryUsage[$test], | |
]) . "\n"; | |
} |
You're testing an optimized merge strategy here - you first collect all arrays you need to merge and then merge them all together at once.
You should've tested more common merge scenario - $out = array_merge($out, $arr);
because this is what you're doing with array_push
. In this case array_merge
looses with a large margin.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr 5 2018 08:53:57) ( NTS )