double quotes suck
most people always do this in php:
$x = "string";
$y = "some text with a $x in it";
result is:
some text with a string in it
i always tell everybody NOT to do this because its slow but they always do it anyway.
now for the non beliefers and fools who do it anyway, i wrote a dirty little "script" to show you how slow is really is.
just test it and before you tell me its only "micro optimization", think about a big website with many of those string assignments and many, many more requests on each page on the website that loads all the shit everytime someone requests something...
<?php
$time = microtime();
$time = explode( ' ', $time );
$time = ( $time[1] + $time[0] );
$begintime = $time;
$x = '1233434545';
for( $i = 0; $i < 1000000; $i++ ) {
$q = 'SELECT * FROM bla WHERE id = '.$x;
}
$time = microtime();
$time = explode( ' ', $time );
$time = $time[1] + $time[0];
$endtime = $time;
$totaltime = ( $endtime - $begintime );
echo 'with \' parsed in '.$totaltime.' seconds<br />';
###
$time = microtime();
$time = explode( ' ', $time );
$time = ( $time[1] + $time[0] );
$begintime = $time;
$x = '1233434545';
for( $i = 0; $i < 1000000; $i++ ) {
$q = sprintf( "SELECT * FROM bla WHERE id = %s", $x );
}
$time = microtime();
$time = explode( ' ', $time );
$time = $time[1] + $time[0];
$endtime = $time;
$totaltime = ( $endtime - $begintime );
echo 'with sprintf parsed in '.$totaltime.' seconds<br />';
###
$time = microtime();
$time = explode( ' ', $time );
$time = ( $time[1] + $time[0] );
$begintime = $time;
$x = '1233434545';
for( $i = 0; $i < 1000000; $i++ ) {
$q = "SELECT * FROM bla WHERE id = $x";
}
$time = microtime();
$time = explode( ' ', $time );
$time = $time[1] + $time[0];
$endtime = $time;
$totaltime = ( $endtime - $begintime );
echo 'with " parsed in '.$totaltime.' seconds<br />';
?>
okay... because everybody is to lazy to run the script:
with ' parsed in 0.17716002464294 seconds
with sprintf parsed in 0.85404491424561 seconds
with " parsed in 1.4009871482849 seconds
[updated: 04. April 2008 - PHP v.5.1.6]
Sep 1st 2007
holy shit. oops
thanks for proving this to me
Sep 6th 2007
using “,” in echo is also faster… check it out (echo ‘a’,$var,’b';)
Sep 6th 2007
dont know if its faster but it only works with echo or print. you cant assign vars with , this would end up in: Parse error: syntax error, unexpected ‘,’
Feb 20th 2008
Single quotes is definitely faster for me, however the other two results are reversed. sprintf is slower than double quotes.
Apr 7th 2008
I had some fluctuating times with 100k samples, so I upped it to a million per type. Sprintf was slowest by far, and single quote was fastest, but double quote wasn’t that far behind. I don’t have the stats right in front of me, unfortunately!