4

I am working to optimize my PHP code and found out that you can speed up echoing in these ways - exactly, you can replace echo "The name of the user is $name" . "."; with:

  • 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'd like not only to see benchmarks, but also some technical explaination, if possible.

Giulio Muscarello
  • 1,312
  • 2
  • 12
  • 33

3 Answers3

11

Firstly, this is micro optimization and you're probably better paying for a faster server and developing more product then spending hours and hours micro optimizing. However according to http://micro-optimization.com/ here are the results:

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

and

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

chrislondon
  • 12,487
  • 5
  • 26
  • 65
  • Agreed with this answer. As for double and single quotes and the concatenation operator I would simply recommend using a standardized approach that suits your code style. – The Thirsty Ape Jun 09 '13 at 17:45
  • Also meaning, single quotes are superior to double quotes by 14%. – untill May 20 '16 at 09:47
  • I already disliked sprintf() because I think it obfuscates. I'm glad to see that my preferred method is faster as well. – TecBrat Nov 17 '16 at 17:51
  • 1. incorrect results provided (micro-optimization.com's fault) 2. incorrect conclusion on the single/double quotes, the first 2 versions provided are behaving differently, `echo 'The name of the user is '.$name.'.';` is creating a unique string which is echoed, `echo "The name of the user is", $name, ".";` is using the "echo" keyword once, but this is a shorthand for calling echo 3 times, respectively with the arguments 3. "echo" behaves differently depending on the SAPI (cli, apache, fcgi,...) used – Patrick Allaert May 11 '17 at 12:56
3

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

That said, the best ways to optimize strings is to pop them into a list and then concatenation the list. Have a look at this post as a good starting point.

Gevious
  • 3,214
  • 3
  • 21
  • 42
3

The variation using sprintf() is quite sure 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"; actually compiles to three single ZEND_ECHO opcodes, which means that the output layer is called multiple times which can be quite slow, depending on the SAPI used. It doesn't make a lot of difference whether you are using echo "abc $n xyz"; or echo "abc " . $n . " xyz"; since they both compile to cocatenation operations.

pp3345
  • 31
  • 3