25

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?

David
  • 208,112
  • 36
  • 198
  • 279
ina
  • 19,167
  • 39
  • 122
  • 201
  • I would say that, it depends from where that data is coming from... user input or system input – Prix Jul 23 '10 at 07:20
  • Would there be performance differences? i.e., more processor time with each? – ina Jul 23 '10 at 07:22
  • 1
    possible duplicate of [PHP - "Sal's mall is $emo" vs "Sal's mall is ".$emo - string with quotes concatenation efficiency](http://stackoverflow.com/questions/3394166/php-sals-mall-is-emo-vs-sals-mall-is-emo-string-with-quotes-concaten) – Dan Grossman Jan 23 '11 at 22:44
  • 1
    /me waves at the sitepoint celebrity dan grossman. – ina Jan 31 '11 at 20:22
  • 1
    Must read: [Disproving the Single Quotes Performance Myth (Jan 2012; by NikiC)](http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html) – hakre Oct 16 '13 at 10:38
  • Maybe it depends on what system you're using? Single quotes were faster on the x86 olllld server I used years ago when this was posted – ina Oct 17 '13 at 05:07

10 Answers10

27

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)

Blizz
  • 8,082
  • 2
  • 33
  • 53
  • 8
    "everyone who did the test..." data source? – ina Jul 23 '10 at 07:34
  • 2
    http://classyllama.com/development/php/php-single-vs-double-quotes/ http://www.procata.com/blog/archives/2005/03/08/microbenchmarks-of-single-and-double-qouting/ Here are 2. google can give you plenty more. – Blizz Jul 23 '10 at 07:41
  • I think test is even not required. It is just a matter of number of processor instructions. The less you have (that can be easily guessable in this case), the faster you are. – snowflake Jul 23 '10 at 08:14
  • The parsing is just done once. There is no additional parsing for double quoted strings. – Gumbo Jul 23 '10 at 08:14
  • Of course the parsing is done just once. But the the steps within the parsing-proccess are meant. With double quotes the parser has to add the step of variable-interpolation to its parsing-chain. – Fidi Jul 23 '10 at 08:37
  • http://www.phpbench.com/ – RobertPitt Jan 23 '11 at 23:03
  • 2
    If there was *ever* a relevant performance reason it makes no difference now - http://nikic.github.io/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html – user2864740 Sep 19 '15 at 04:33
  • This is BS. There is maybe only a very slight performance difference between using double and single quotes. Difference between the two is that the parser will use variable-interpolation in double-quoted strings, but not with single-quoted strings. So maybe in very early days this could have been a performance difference but as told here in this answer above never a MARGINALLY difference. Resources are coding guidelines FIG / PSR http://www.php-fig.org/psr/ and https://github.com/zikula/core/wiki/Coding-Standards#singledouble-quotes What are your sources for this information you gave? – Bojoer Nov 11 '16 at 07:09
  • 2
    Dude.. seriously? Not only are you responding to an answer that is more than 6 years old, you are basically saying exactly the same thing. That is what "marginally better" means: "very slight". – Blizz Nov 12 '16 at 08:32
14

The difference between single and double quotes in PHP is that double quotes are "intelligent" in that they will parse for variables when being read, while single quotes are "dumb" and will not try to parse any character in the string.

These result in some minor differences in what characters you can use; basically, the only character you need to escape when using single quotes is a single quote itself:

'\''

While if you use double quotes you have to escape other characters:

"\$"

But it also allows for some nifty things like adding a new-line to the end:

"my string\n"

With single quotes you would have to do a concatenation:

'my string' . chr(10)
'my string' . "\n"

Generally, single quotes are faster because they are "dumb".

However, normally one should not really worry about these issues, that is called Premature optimization, and should be avoided.

A couple of words about optimization: generally one should first write the program the way it should work, and then find the biggest bottlenecks and fix those particular ones. If string speed really is an issue for you in PHP, you might want to consider switching to another language.

Regarding speed: you probably want to focus more on memory usage than on CPU time. In these cases the CPU time could be considered pretty constant. CPU time is more relevant when writing algorithms that will iterate many times.

Regarding concatenations: the more you concatenate strings using the dot-operator, the more memory you will be using.

Consider this:

$str1 = 'asdf';
$str2 = 'qwer';

// this will result in more memory being allocated for temporary storage
echo $str1 . $str2;

// this will not allocate as much memory as the previous example
echo $str1;
echo $str2;
thnee
  • 5,817
  • 3
  • 27
  • 23
9

I generally feel that using string interpolation ("Hi, my name is $name") is better from a legibility standpoint.

Flavius Stef
  • 13,740
  • 2
  • 26
  • 22
6

For performance, as others have proven, it is marginally faster to use single quotes rather than double quotes.

Single quotes, if applied to readability science and kept away from subjectivity actually adds more "noise". Noise and how it relates to readability is talked a lot about in the book Clean Code and one could conclude that the more non-whitespace you have to see, the more it hinders readability. If applied to subjectivity, most places that I've taken the time to read actually prefer single over double quotes.

Use your judgement.

$var = "My $string with $lots of $replacements."

Is much more readable than:

$var = 'My ' . $string . ' with ' . $lots . ' of ' . $replacements . '.';

I'll admit that:

$var = "My string.";

Looks almost the same as:

$var = 'My String.';

However the latter introduces less noise and when there's lots of code around it every little bit helps, not to mention the other benefits you get from using single quotes.

In the end, I prefer to KISS. Use single quotes unless you need double quotes. Simple convention that is easier to type, easier to maintain, easier to parse and easier to read.

Tres
  • 5,604
  • 3
  • 19
  • 17
0

The single quoted string is better option than double quoted string while concatenating the variables. click the link for better understanding...

http://www.codeforest.net/php-myth-busters-using-single-quotes-on-string-is-faster-then-double-quotes

DkPathak
  • 452
  • 1
  • 4
  • 16
0

It doesn't matter from syntax perspective. Both variants are correct. Use what you feel more comfortable.

Personally, I feel better when using the $string="Hi, my name is $name", because you don't need to mess with quotes. Just image the complex SQL query with, let's say, 10 variables...

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
0

PHP is pretty slow:

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-088-introduction-to-c-memory-management-and-c-object-oriented-programming-january-iap-2010/lecture-notes/MIT6_088IAP10_lec01.pdf

Slide #3

So don't worry too much about little optimizations like these.

Focus more on using APC to cache your code into byte code though. You'll see big speed gains for the project.

Homer6
  • 15,034
  • 11
  • 61
  • 81
0

Personally, if it's just a normal variable, or even a class property, I'd write it like this:

$newVarA = "This is some text with a $variable";
$newVarB = "This is some more text, written in $settings->language";

However, if I'm using array values then I'll concatenate with single quotes.

$newVarC = 'This is some text from a ' . $text['random'] . ' array';

Hope this makes sense. It's all about finding convention and sticking to it.

Martin Bean
  • 38,379
  • 25
  • 128
  • 201
  • Your array example works just fine without the concatenation. `... from a {$text['random']} array`, or `... from a $text[random] array`. You'd only *have* to use the {} method if you're referencing a multi-dimensional array, as PHP's parser isn't greedy. `$array[x][y]` will get parsed as ``. – Marc B Jul 23 '10 at 17:26
  • Yes. But I find using braces in strings just gets a bit ugly to me. Like I say, it's just an example of how I personally concatenate strings with variables. – Martin Bean Jul 24 '10 at 09:22
0

My motto and answer is: Leave it to the compilers to write machine code. I will tell you what I mean...

Use single quotes when you don't need to include PHP variables, otherwise use double quotes. Dont bother about performance just use APC on production servers. Instead focus on writing the most maintainable code; use comments, double quotes etc. properly even though they may slow code down. Every optimization that decreases maintainability / readability of code is bad, leave it to the opcode-cachers and compilers to turn your code into machine code, don't do it yourself... obfuscating your source code because of optimization fires back.

Gabor de Mooij
  • 2,997
  • 17
  • 22
-5
$string='Hi, my name is '.$name

This is the best way, in the sense of php and html combination!

or like this:

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

This is the old way!

Or like this:

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

This is what a programmer coming from Visual Basic or other Client Programming languages would write!

I hope I was helpful.

Josh
  • 10,961
  • 11
  • 65
  • 108
stooni
  • 7
  • 2
  • 1
    I disagree that `"Hi, my name is $name"` is "old", and that `'Hi, my name is '.$name` is somehow better! – Josh Jan 23 '11 at 22:47