Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save KVytyagov/895dc063ad7126ecb967f8503c47ae0c to your computer and use it in GitHub Desktop.
Save KVytyagov/895dc063ad7126ecb967f8503c47ae0c to your computer and use it in GitHub Desktop.
Performance test array_merge vs array_push in loop
<?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";
}
@KVytyagov
Copy link
Author

Array count: 100; items in array: 100; iterations: 500
Merge
[avg]: 0.00016187906265259 [min]: 0.00013184547424316 [max]: 0.0010769367218018 [mem_usage]: 6291456
ArrayPush
[avg]: 0.00025954294204712 [min]: 0.00023102760314941 [max]: 0.00055813789367676 [mem_usage]: 6291456

PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr 5 2018 08:53:57) ( NTS )

@Stalinko
Copy link

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