PHP has many ways to concatenate strings, and many ways to expand variables inside strings. But which is the fastest?
the rule is simple, use double quotes for concatenation and use curly braces for variable expansion. example:
$var = 'foo';
echo "This is a {$var} notation";
for more details, see the rules section below and the tests section below that.
- Always use double-quoted strings for concatenation, because it's the fastest method. The only exception is when you're concatenating a variable with a literal string that has no variables in it, then you can use single-quoted strings for a tiny bit of extra performance.
- Put your variables in
"This is a {$variable} notation"
, because it's the fastest method which still allows complex expansions like"This {$var['foo']} is {$obj->awesome()}!"
. You cannot do that with the"${var}"
style. - Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.
- If you think another method such as
sprintf()
or'this'.$var.'style'
is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer!
refer to the source of tests results here