Last active
October 9, 2019 10:45
-
-
Save KVytyagov/7fa062de71e338a0feb1655432e38a57 to your computer and use it in GitHub Desktop.
Check performance to get unique values from array
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 | |
$iterations = 10; | |
$originValuesTo = 10000; | |
$duplicateValuesTo = 10000; | |
$duplicatesCount = 2; | |
$a = range(0, $originValuesTo); | |
$b = range(0, $duplicateValuesTo); | |
function convertToStringsArray(array $intArray): array { | |
return array_map(function ($val): string { | |
return (string) $val; | |
}, $intArray); | |
} | |
$a = convertToStringsArray($a); | |
$b = convertToStringsArray($b); | |
$arrayToTest = array_merge($a, ...array_fill_keys(range(0, $duplicatesCount), $b)); | |
function arrayKeysForeachMethod(array $arr) { | |
$map = []; | |
foreach ($arr as $item) { | |
$map[$item] = null; | |
} | |
return array_keys($map); | |
} | |
function arrayKeysReduceMethod(array $arr) { | |
$map = array_reduce($arr, function (array $carry, $item): array { | |
$carry[$item] = null; | |
return $carry; | |
}, []); | |
return array_keys($map); | |
} | |
function arrayValuesUnique(array $arr) { | |
return array_values(array_unique($arr)); | |
} | |
$testFunctions = [ | |
'arrayKeysForeachMethod', | |
'arrayKeysReduceMethod', | |
'arrayValuesUnique', | |
]; | |
foreach ($testFunctions as $functionName) { | |
$results = []; | |
for($i = 0; $i < $iterations; ++$i) { | |
$start = microtime(true); | |
$memoryPeakOnStart = memory_get_peak_usage(true); | |
shuffle($arrayToTest); | |
$res = $functionName($arrayToTest); | |
$time = microtime(true) - $start; | |
$memoryPeakIncrease = memory_get_peak_usage(true) - $memoryPeakOnStart; | |
$results['times'][] = $time; | |
$results['memoryPeak'][] = $memoryPeakIncrease; | |
} | |
echo sprintf( | |
"Method '%s'\n\tavgTime: %f\n\tavgMemoryPeak: %d\n", | |
$functionName, | |
array_sum($results['times']) / count($results['times']), | |
array_sum($results['memoryPeak']) / count($results['memoryPeak']) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
=====
parameters
result
====
parameters
result
=====
parameters
result
=====
parameters
result
=====
parameters
result