Created
October 22, 2019 07:28
-
-
Save KVytyagov/bdd4a79ce436adaab9e0f98abee57e2e to your computer and use it in GitHub Desktop.
concat string comparison
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**7; | |
$part1 = 'some_part1_string'; | |
$part2 = 'some_part2_string'; | |
$part3 = 'some_part3_string'; | |
$part4 = 'some_part4_string'; | |
function singleQuotesConcat(string $p1, string $p2, string $p3, string $p4): string { | |
return $p1 . '-' . $p2 . '-' . $p3 . '-' . $p4; | |
} | |
function doubleQuotesConcat(string $p1, string $p2, string $p3, string $p4): string { | |
return "{$p1}-{$p2}-{$p3}-{$p4}"; | |
} | |
function sprintfConcat(string $p1, string $p2, string $p3, string $p4): string { | |
return sprintf('%s-%s-%s-%s', ...func_get_args()); | |
} | |
function implodeConcat(string $p1, string $p2, string $p3, string $p4): string { | |
return implode('-', func_get_args()); | |
} | |
$testFunctions = [ | |
'singleQuotesConcat', | |
'doubleQuotesConcat', | |
'sprintfConcat', | |
'implodeConcat', | |
]; | |
foreach ($testFunctions as $functionName) { | |
$results = []; | |
for($i = 0; $i < $iterations; ++$i) { | |
$start = microtime(true); | |
$memoryPeakOnStart = memory_get_peak_usage(true); | |
$res = $functionName($part1, $part2, $part3, $part4); | |
$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
result