Here’s an interesting item I doubt many PHP developers know. There’s a performance hit to using strings with double quotes instead of single quotes. According to an article written about simple PHP Optimizations by the helpful folks at google you may actually be hurting yourself by using double quotes in strings that use variables. Most programmers use this convention because it’s simple to type and easy to read. Apparently, using this convention tells the PHP engine to parse the string, look for variables inside it and replace them. If you use single quotes and concatenation, you won’t have this overhead.
In my simple, unscientific tests, it looks like there’s a 30% difference in performance if us use double-quotes.
I used a for loop with a simple string that used the loops variable inside it and echo’ed the line 100,000 times. I ran this 50 times and took used microtime to compute how long it took for the loop to complete. I did this using all the different combinations they discuss in the article and I did this on a local linux box to make sure network latency wasn’t a factor.
I found that using the comma versus the period for concatenation didn’t affect performance in any significant way. Using double quotes took on average 30% longer to complete.
That’s a significant difference and something to keep in mind when writing code. I have no converted to using double quotes sparingly.
If you’re interested in the methodology, here’s the code that I’m sure someone will pick-apart.
<?php
$start=microtime();
$start=explode(” “,$start);
$start=$start[1]+$start[0];
for ($i=0; $i < 100000; $i++){
echo ‘this is a string with the variable: ‘,$i,chr(10);
}
$end=microtime();
$end=explode(” “,$end);
$end=$end[1]+$end[0];printf(“generated in %f seconds\n”,$end-$start);
?>