Benchmarking PHP: Single vs Double Quotes


There has always been a heated debate over the correct usage of quotes. Should you use single quotes or double quotes? Should you embed variables into double quotes?

I have done a quick benchmark of the 3 options you have available to you. You may make your own conclusions…

Benchmark Code Samples:

v1.php:

<?PHP 

for ($i = 0; $i < 100000; $i++) { 
        $n = "string".$i; 
} 

?>

v2.php:

<?PHP 

for ($i = 0; $i < 100000; $i++) { 
        $n = 'string'.$i; 
} 

?>

v3.php:

<?PHP 

for ($i = 0; $i < 100000; $i++) { 
        $n = "string$i"; 
} 

?>

All 3 samples of code do exactly the same thing the same number of times, however the execution time of each script is different.

The benchmarks were run on a P2 400MHz with 192MB RAM. The linux "time" command was used to calculate the actual CPU time used by each script. The results are as follows:

# time php v1.php
real 0m1.260s
user 0m1.224s
sys 0m0.032s

# time php v2.php
real 0m1.271s
user 0m1.224s
sys 0m0.036s

# time php v3.php
real 0m1.973s
user 0m1.944s
sys 0m0.032s

Notice how the v1.php and v2.php timings are very similar, it is interesting that using double quotes without embedded variables is actually faster than using single quotes.

The marked difference is when it comes to using an embedded variable in v3.php. Note how the execution time increases by 0.7s, a 50% increase in execution time.

Leave a Reply