Question:
In order to collect a string, you can use two options. The first one using double quotes (the data is parsed) for example:
$text = "Здесь любой текст и переменная $test";
Or the second option using concatenation:
$text = 'Здесь любой текст и переменная '.$test;
Which option will work faster? And does the difference in speed depend on the number of variables in the line? Just heard the opinion that concatenation takes longer. I would like to hear the opinion of experts.
Answer:
since yesterday with @AlexeyShimansky we touched on tests, and @StackOverflow shared a link to an article as ancient as dinosaurs with some tests from 2008, I decided to check one of these tests in 2017.
Hardware from almost the same era i7-980x and 10 GB of memory in stock
win10x64, Open Server, check for pkhp 5.6 and 7.0.22.
the launch of test functions has been rewritten somewhat.
for($i = 1; $i <= 4;$i++){
$f = "quotes_$i";
$ts = microtime(true);
call_user_func($f, $_1, $_2, $_3, $_4, $_5, $_iterator);
$time = microtime(true) - $ts;
print "$f - $time\n";
}
4 functions are tested, each with 5 million iterations, 5 variables are substituted into the string:
- substitution in strings like
"qwe $var asd"
- substitution in strings like
"qwe {$var} asd"
- concatenate with single quotes
'qwe'.$var.'asd'
- using
sprintf
for pkhp 5.6×32 the results are as follows (5 starts, average):
1. 4,143 сек
2. 3,827 сек
3. 6,866 сек
4. 12,378 сек
when run in the console, the result is similar.
for pkhp 5.6×64, the time slightly increases (hereinafter, 3 starts, average)
1. 4,198 сек
2. 4,182 сек
3. 8,646 сек
4. 12,572 сек
When switching to php 7.x, the situation changes dramatically
1. 1,625 сек
2. 1,612 сек
3. 2,862 сек
4. 13,886 сек
in contrast to 5.6 for pxp 7.x x64 acceleration is observed
1. 1,149 сек
2. 1,156 сек
3. 2,871 сек
4. 12,143 сек
hence the conclusions:
- calling the formatting function
sprintf
obvious outsider, and this is understandable, since stack switching, etc. also requires decent resources. - x64 version for 5.6. works a little longer than x32, although in the case of php 7.x the situation is the opposite and the x64 variant wins.
- the variant with concatenation always loses to the variant with substitution in a string, and if for pxp 5.6 it is 1.5-2 times, then for pxn 7 it is 2 times or more.
- in php 7. options 1 and 2 are substituted in a string in double quotes are identical in speed, although in 5.6 the first one lost a little.
- php 7 is 2.5-3.5 times faster in these operations than 5.6.