Single quotes or double quotes for variable concatenation?

ina picture ina · Jul 23, 2010 · Viewed 49.7k times · Source

Is it better to concatenate a variable (say, $name) into an existing string (say, $string) like this:

$string='Hi, my name is '.$name

or to embed the variable in the string like this:

$string="Hi, my name is $name";

or is it better to use a function like this:

$string=sprintf("Hi, my name is %s",$name);

Which is better in terms of processor time/efficiency?

Answer

Blizz picture Blizz · Jul 23, 2010

Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.

However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.

So for the performance people: use single quotes. For the "i like my code readable"-people: double quotes are a lot better for the legibility, as Flavius Stef already pointed out.

Edit: One thing though - If you are going to use a a single dollar in your string without a variable, use single quotes for sure! (http://www.weberdev.com/get_example-3750.html points out that it will take 4 times longer to parse those strings)