I always enjoy doing interviews and asking potential candidates what the difference between single quotes and double quotes are in PHP. Most people have the basic understanding that single quotes are not interpreted by the compiler whereas double quotes are processed while the page is being executed. The follow up question is typically which one they prefer; this answer is always 50/50. I have always been a fan of single quotes thinking them to be faster…
[code]
<?php
$string = ‘This is a string’;
$string2 = ‘This is a string that includes a ‘ . $string;
$string3 = ‘One last string include a ‘ . $string2;
echo $string;
echo $string2;
echo $string3;
[/code]
Next, let’s do almost the exact same code using double quotes:
[code]
<?php
$string = “This is a string”;
$string2 = “This is a string that includes a $string”;
$string3 = “One last string include a {$string2}”;
echo $string;
echo $string2;
echo $string3;
[/code]
Once finished, I proceeded to run my speed comparison tool hosted on GitHub. The results are fascinating! The single quote example ran just under 7,400 times in 10 seconds. The double quote example ran just under 7,900 times in 10 seconds. A 7% speed increase by using double quotes.
At first glance, I was surprised by this result. But, then I stopped and thought about it for a second. If double quoted strings are already being processed by the compiler, it should deal quite well with processing the variables within them; whereas, single quoted strings would need to be evaluated and then determined that they need to be processed because I’m concatenating a string with it!
I then proceeded to adjust the examples as follows:
[code]
<?php
$string = ‘This is a string’;
echo $string;
[/code]
Next, let’s do almost the exact same code using double quotes:
[code]
<?php
$string = “This is a string”;
echo $string;
[/code]
These results were more of what I expected to see. The single quote example ran nearly 7,800 times while the double quoted example ran just under 7,300 times. This makes much more sense, since the single quoted string requires no processing and the double quoted string needs processing (even though there is nothing to process) slows things down a bit.
Summary
Well, I think my mind has been officially changed – now I just need to change my coding style – when I need to include variables inside of variables in PHP I am going to use double quoted strings. However, when I have more of constant based string I will continue to use single quoted strings for the exact reason that they do not get executed by the compiler.