Skip to content

PHP Myth Busters: Using single quotes on string is faster than double quotes

I got idea today talking to my co-worker and friend Zoran about starting a series of article called: PHP Myth Busters. This series will deal with some PHP Myths and try to Confirm them or Bust them. Please, feel free to contribute by sending some myths around PHP which you would like to put to the ultimate test.

I will start with a simple Myth today:

Using single quotes on a string in echo statement is faster then using double quotes!

When I started the research on this, I was wondering how to even prove (or disapprove) such a statement. We can not just measure the time in ms and that’s it.

My research of the internet has lead me to PECL extension called Vulcan Logic Disassembler 🙂 or VLD, which can be used to see the generated PHP Opcode (the compiled form of a PHP script).

So I installed the extension and started testing.

First, double quotes:

[code lang=”php”]
echo “This is a string”;
[/code]

Opcode looks like this:

[code lang=”php”]
ECHO ‘This is a string’
[/code]

Then, I tried single quotes:

[code lang=”php”]
echo ‘This is a string’;
[/code]

Opcode looks like this:

[code lang=”php”]
ECHO ‘This is a string’
[/code]

Same result.

MYTH IS BUSTED!

But wait. As I wanted to call this myth busted, I played a little with adding some variables in the game:

[code lang=”php”]
echo “This is a $variable”;
[/code]

I got this opcode:

[code lang=”php”]
INIT STRING ~0
ADD_STRING ~0 ~0 ‘This’
ADD_STRING ~0 ~0 ‘ ‘
ADD_STRING ~0 ~0 ‘is’
ADD_STRING ~0 ~0 ‘ ‘
ADD_STRING ~0 ~0 ‘a’
ADD_STRING ~0 ~0 ‘ ‘
ADD_VAR ~0 ~0 !0
ECHO ~0
[/code]

OMG. Very much opcode generated out of one simple echo statement. Let us try to optimize that somehow:

[code lang=”php”]
echo “This is a ” . $variable;
[/code]

I am using concatenation this time, and it is much simpler opcode now:

[code lang=”php”]
CONCAT ~0 ‘This is a ‘ !0
ECHO ~0
[/code]

Wow, that is obviously much faster then before. Even PHP manual agrees:

Parsing variables within strings uses more memory than string concatenation. When writing a PHP script in which memory usage is a concern, consider using the concatenation operator (.) rather than variable parsing.

Some people on the net suggest that the fastest form is this:

[code lang=”php”]
echo “This is a ” , $variable;
[/code]

Yes, a comma. You can use it in echo statement. This produces :

[code lang=”php”]
ECHO ‘This is a ‘
ECHO !0
[/code]

This is the fastest way, as it is not duplicating the string like in Concatenation.

I know, you will tell me that it is not worth it, but it isn’t much of a change to use commas to concatenate parameters in echo statements. If you have many, it could be a great optimization.