Concatenation, multiple parameters or sprintf?

I am working on optimizing my PHP code and found out that you can speed up the echo in this direction - you can replace echo "The name of the user is $name" . "."; echo "The name of the user is $name" . "."; on the:

  • echo 'The name of the user is '.$name.'.';
  • echo "The name of the user is", $name, ".";
  • echo sprintf("The name of the user is %s", $name);

Which one is the fastest? I would like not only to see benchmarks, but also technical explanations, if possible.

+4
source share
3 answers

The first is micro-optimization, and you probably pay better for a faster server and develop more products, and then spend hours and hours on micro-optimization. However, according to http://micro-optimization.com/ , the results are:

sprintf () is slower than double quotes 138.68% (1.4 times slower)

and

sprintf () is 163.72% slower than single quotes (1.6 times slower)

+11
source

The above comments are relevant. There are better ways to optimize your code.

However, the best ways to optimize strings are to list them and then merge the list. Check out this post as a good starting point.

+3
source

The variant using sprintf() is quite sure that it is the slowest of all, since function calls in PHP are quite expensive, and sprintf() will have to parse the format string. Using something like echo "abc ", $n, " xyz"; , is actually compiled into three single ZEND_ECHO , which means that the output level is called several times, which can be quite slow, depending on the SAPI used. It doesn't really matter if you use echo "abc $n xyz"; or echo "abc " . $n . " xyz"; echo "abc " . $n . " xyz"; as both of them are compiled into cocatinization operations.

+3
source

Source: https://habr.com/ru/post/1485309/


All Articles