Skip to content

Instantly share code, notes, and snippets.

@KVytyagov
Created October 22, 2019 07:28
Show Gist options
  • Save KVytyagov/bdd4a79ce436adaab9e0f98abee57e2e to your computer and use it in GitHub Desktop.
Save KVytyagov/bdd4a79ce436adaab9e0f98abee57e2e to your computer and use it in GitHub Desktop.
concat string comparison
<?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'])
);
}
@KVytyagov
Copy link
Author

PHP 7.2.22-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Sep  2 2019 12:54:33) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.22-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
    with Xdebug v2.7.2, Copyright (c) 2002-2019, by Derick Rethans

result

Method 'singleQuotesConcat'
	avgTime: 0.000003
	avgMemoryPeak: 0
Method 'doubleQuotesConcat'
	avgTime: 0.000003
	avgMemoryPeak: 0
Method 'sprintfConcat'
	avgTime: 0.000003
	avgMemoryPeak: 0
Method 'implodeConcat'
	avgTime: 0.000003
	avgMemoryPeak: 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment