Skip to content

Instantly share code, notes, and snippets.

@derhofbauer
Created March 28, 2019 09:02
Show Gist options
  • Save derhofbauer/3f47da68f9b88b04120fa84cf468a0c6 to your computer and use it in GitHub Desktop.
Save derhofbauer/3f47da68f9b88b04120fa84cf468a0c6 to your computer and use it in GitHub Desktop.
Compare string concatenation speed to array imploding, when it comes to combining strings
<?php
/**
* I was explaining how strings and arrays are stored differently in RAM to my
* students and I told them, that array imploding is much more efficient than
* traditional string concatenation.
*
* I created this benchmark to prove my point.
*/
$iterations = 100000;
$test_string = 'foobar';
function echo_n ($str, $n_and_r = false) {
if ($n_and_r === true) {
echo "<p>{$str}</p>";
} else {
echo "{$str}<br>";
}
}
echo_n("Starting Benchmark with $iterations iterations", true);
// string concat
$start = microtime(true);
echo_n("Start: $start (concat)");
$string = '';
for ($i = 0; $i <= $iterations; $i++) {
if ($i > 0) {
$string .= " $test_string";
} else {
$string .= "$test_string";
}
}
$end = microtime(true);
$duration1 = $end - $start;
echo_n("End: $end");
echo_n("Duration: $duration1 milliseconds");
// array implode
echo_n("");
$start = microtime(true);
echo_n("Start: $start (array)");
$array = [];
for ($i = 0; $i <= $iterations; $i++) {
$array[] = $test_string;
}
$string2 = implode(' ', $array);
$end = microtime(true);
$duration2 = $end - $start;
echo_n("End: $end");
echo_n("Duration: $duration2 milliseconds");
// Do both methods produce the same result?
if ($string === $string2) {
echo_n("Both generated strings are the same! Yay! :D", true);
}
// Results
if ($duration1 < $duration2) {
$factor = round($duration2 / $duration1, 1);
echo_n("The winner is string concatenation, with a duraction of $duration1 over $duration2, that equals a factor of $factor", true);
} elseif ($duration1 > $duration2) {
$factor = round($duration1 / $duration2, 1);
echo_n("The winner is array imploding, with a duraction of $duration2 over $duration1, that equals a factor of $factor", true);
} else {
echo_n("We have no winner, both methods are equal.", true);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment