Edit – My question is not stricktly limited to preformance, I would also like to know the pitfalls of each and if there is a condition where one should be used over the other.
Which is better to use to concat a string in PHP?
Option A: Use the . operator to concat the strings
$string1 = "hello ";
$string2 = $string1 . "world !";
Option B: Use double quotes
$string1 = "hello ";
$string2 = "$string1 world !";
I realize that both will in fact do the same thing, and in my personal development I prefer to use the . operator.
My question only arises because i’ve read that the . operator forces php to re-concatenate with each new string, so in the example:
$string1 = "hello ";
$string2 = "world";
$string3 = $string1.$string2." !";
would actually run slower than
$stirng1 = "hello";
$string2 = "world";
$string3 = "$string1 $string2 !";
Reference: PHP Language Operators > Strings
I think before you start worrying about it, you need to see if it is even worth thinking about. I did think about it, and wrote the following tiny script and ran it to see what the benchmarks were like.
For each loop, I made 100,000 passes. Now I didn’t print my strings anywhere so if the PHP optimizer takes all of my work away because of that, then I apologize. However looking at these results, you are looking at a difference of about 0.00001 second for each.
Before you optimize for anything other than readability, use a profiler and see where your hotspots are. If you run tens of millions of concatenations, then you may have an argument. But with 1000, you are still talking about a difference of 0.01 seconds. I’m sure you could save more than 0.01 seconds just by optimizing SQL queries and the like.
My evidence is below….
Here’s what I ran:
Here are the results: