Some have claimed that double-quoted string evaluation in PHP run at the same speed as single-quoted (or constant) string evaluation. As a reminder, double-quoted strings are useful because they permit variables to be evaluated inside of them, whereas single-quoted strings do not.
Below I will consider the veracity of the claim.
Let us consider three cases:
- A constant string at the end of which we append another string.
- A constant string in the middle of which we insert another string.
- A constant string by itself.
Case 1
Consider this PHP program:
$a = 5; for ($i = 0; $i < 10000000; $i++) { echo "This is a test $a"; }
versus this equivalent program:
$a = 5; for ($i = 0; $i < 10000000; $i++) { echo 'This is a test' . $a; }
In this test, a common situation occurs in which a variable is included within a double-quoted string. The single-quoted equivalent requires that we concatenate a constant string and the variable.
At the command-line, we can run each of these programs and get the execution times for each like so:
time php ./program.php > /dev/null
The result is as follows:
In three runs of the double-quoted string program, I got times of:
49, 47 and 42 seconds. (Average 46 sec.)
In three runs of the single-quoted string program, I got userland running times of:
37, 40, and 40 seconds. (Average 39 seconds.)
This means the double-quoted string program ran 18% longer (slower) than the single-quoted equivalent.
Case 2
Now let's consider the case of inserting a string inside of a constant string:
$a = 5; for ($i = 0; $i < 10000000; $i++) { echo "This is a test $a etc."; }
versus this equivalent program:
$a = 5; for ($i = 0; $i < 10000000; $i++) { echo 'This is a test' . $a . 'etc.'; }
Times for the double-quoted program (7 runs) are 51, 48, 46, 51, 46, 51, 46 for an average of 48.
Times for the single-quoted program (7 runs) are 47, 47, 46, 44, 43, 44, 44, for an average of 45.
In this case, double-quoted strings were evaluated only 7% slower than single-quoted.
Case 3
Finally let's consider simple constant strings:
for ($i = 0; $i < 10000000; $i++) echo "This is a test etc.";
versus this equivalent program:
for ($i = 0; $i < 10000000; $i++) echo 'This is a test etc.';
These two run at essentially the same speed, as is to be expected because PHP converts the source code into an internal, compiled format that expresses a double-quoted constant string that lacks variables expressions within it the same as a single-quoted string.
Double-quoted times: 22, 22, 21, 21, 22, 21, 22 seconds for an average of about 22.
Single-quoted times: 21, 21, 23, 22, 22, 22, 22 seconds for an average of 22.
Conclusion
The claim that single- and double-quoted strings evaluate at the same speed is true if and only if the double-quoted strings do not contain any variable expressions. This is an important qualification, because double-quoted strings are often used with variable expressions inside of them.