Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenation, multiple parameters or sprintf?

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.

like image 830
Giulio Muscarello Avatar asked Dec 03 '22 22:12

Giulio Muscarello


2 Answers

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)

like image 114
chrislondon Avatar answered Dec 09 '22 15:12

chrislondon


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.

like image 38
Gevious Avatar answered Dec 09 '22 15:12

Gevious