String interpolation and concatenation

In PHP 7, string interpolation has been optimized with a new string analysis algorithm. This means that string interpolation is now much faster than concatenation and that what used to be true about concatenation and performance is no longer the case. Let's take the following code example in order to measure the new algorithm's performance:

// chap3_string_interpolation.php

$a = str_repeat(chr(rand(48, 122)), rand(1024, 3000));

$b = str_repeat(chr(rand(48, 122)), rand(1024, 3000));

$start = microtime(true);

for ($x = 0; $x < 10000; $x++) {
$$x = "$a is not $b";
}

$time = microtime(true) - $start;

echo 'Time elapsed: ' . $time . PHP_EOL;

echo memory_get_usage() . ' bytes' . PHP_EOL;

Here are the performance measurements when running this code against PHP 5.6:

The results when running the script against PHP 5.6

And here is the same script with PHP 7:

The results when running the same script against PHP 7.1

PHP 7 is about three to four times faster and consumes more than a third less memory. The lesson to be learned here is to try using PHP 7's string interpolation algorithm as much as possible when dealing with strings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset