Created
February 22, 2018 15:43
-
-
Save EnchanterIO/51afd5c816a764daf866227ce84a07b2 to your computer and use it in GitHub Desktop.
Benchmarks merging two arrays using array_merge and classic foreach loop with manual addition.
This file contains 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 | |
class Benchmark | |
{ | |
/** | |
* @param string $mergeStrategy | |
* @param int $arrayToMergeSize | |
* | |
* @return void | |
*/ | |
public function run(string $mergeStrategy, int $arrayToMergeSize): void | |
{ | |
$startMicrotime = microtime(true); | |
$mergedArray = []; | |
$extraBigArrayToMerge = []; | |
for ($i = 0; $i < 1000000; $i++) { | |
$mergedArray[] = 'hardcoded:'.$i; | |
} | |
for ($i = 0; $i < $arrayToMergeSize; $i++) { | |
$extraBigArrayToMerge[] = 'extra:'.$i; | |
} | |
if ($mergeStrategy === 'array_merge') { | |
$mergedArray = array_merge($mergedArray, $extraBigArrayToMerge); | |
} | |
if ($mergeStrategy === 'normal') { | |
foreach ($extraBigArrayToMerge as $element) { | |
$mergedArray[] = $element; | |
} | |
} | |
$endMicrotime = microtime(true); | |
echo sprintf( | |
"Merging two arrays using '%s' strategy took %d seconds.\n", | |
$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 / 1024 | |
); | |
} | |
} | |
$mergeStrategy = $argv[1]; | |
$extraBigArraySize = $argv[2]; | |
$benchmark = new Benchmark(); | |
$benchmark->run($mergeStrategy, $extraBigArraySize); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment