PHP Strings ‘ vs “

It’s wideley known that PHP supports both ‘ (single quote) and ” (double qoute) for string delimiting.
It’s also widely known that PHP evaluates the DQ (Double Quote) Strings and replaces variables with their actual value. But not a lot has been written about what is actually faster.

Its quite simple: SQ (Single Quotes) is faster. Hands down.

It’s even faster when adding the variable by concatenating multiple strings. Please look at the following code:
//variable used in DQ
$time = microtime();
for($i=0;$i<1000;++$i){
$$i = "Some Random String $i with a number";
}
echo microtime()-$time;
//Variable used in concatenation with DQ
echo '
';
for($i=0;$i<1000;++$i){
$$i = "Some Random String ".$i." with a number";
}
echo microtime()-$time;
//variable used in concatenation with SQ
echo '
';
$time = microtime();
for($i=0;$i<1000;++$i){
$$i = 'Some Random String '.$i.' with a number';
}
echo microtime()-$time;

Code speaks for itself. In order of speed:
1. SQ
2. DQ without concat.
3. DQ with concat.

Why, easy: Single quotes does not require evaluating. DQ without concat requires 1 evaluate. DQ with concat requires 2 evaluations of the string.
So, in conclusion: double quotes are evil!

1 Comment to “PHP Strings ‘ vs “”

  1. jduck
    2010/05/18

    Even if there are no variables to substitute, it still has to make a special comparison for every byte (is it ‘$’ ?) that single quoting will not have to.

    This is the same reason to use puts/fputs instead of printf/fprintf — silly slow downs. Convenience versus performance .. HEHE

Leave a Comment

*

*