Skip to content

Instantly share code, notes, and snippets.

@EnchanterIO
Last active February 22, 2018 15:42
Show Gist options
  • Save EnchanterIO/6e90f828c1b32c894d35267c353e83d2 to your computer and use it in GitHub Desktop.
Save EnchanterIO/6e90f828c1b32c894d35267c353e83d2 to your computer and use it in GitHub Desktop.
Performance of array_merge comparing to normal element addition in a loop
<?php
$mergeStrategy = $argv[1];
$numberOfNewElements = $argv[2];
$isArrayMergeStrategy = $mergeStrategy === 'array_merge';
$isUnionStrategy = $mergeStrategy === 'union';
$list = [
[0],
[1],
];
$startMicrotime = microtime(true);
for ($i = count($list); $i < $numberOfNewElements; $i++) {
if ($isArrayMergeStrategy) {
$list = array_merge($list, [$i => [$i]]);
continue;
}
if ($isUnionStrategy) {
$list[$i] = [$i];
continue;
}
}
$endMicrotime = microtime(true);
echo sprintf(
"Building array of %d elements using %s took %d seconds.\n",
count($list),
$mergeStrategy,
$endMicrotime - $startMicrotime
);
echo sprintf(
"Memory usage is: %d MB.\n",
memory_get_usage() / 1024 / 1024
);
echo sprintf(
"Memory peak was: %d MB.\n",
memory_get_peak_usage(true) / 1024
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment