use of curly braces with string interpolation.

php.internals

Jochem Maas

21 years ago
hi guys, I always use curly braces around vars placed in double quoted strings, I do this for 2 reasons: 1. I believe It helps the engine because the var delimitation is explicit, and this means the interpolation is (should be?) faster. 2. it looks nice (easier to read!) I have tried to test this with a simple script that does a million interations - but I cannot get it to return consistent results - one time with curlies is faster, another its slower. the (php5) script I used to test is included at the bottom of the email for those who are curious. (I haven't been able to find relevant info on either google or php.net - are there any other search engines? ;-) I am interested in knowing whether my first assumption regarding speed of interpolation is (in theory) at all correct. If any of the php gurus would give advice as to use of curly braces in interpolated strings would it be: a, always use them (its faster/better) b, only when absolutely necessary c, go away troll and figure it out for yourself (this one is tempting, n'est pas ;-) d, something I haven't had the presence of mind to think of! kind regards, Jochem. <? class Tester { public $testvar; } $t = new Tester; $t->testvar = 'superduper'; $a = array('junk' => 'notbad!'); var_dump($t, $a); $strs = array(); $start = mktime(); $i = 0; do { $c = 'simplicity' + $i; $strs[] = "{$t->testvar} yadda yadda {$a['junk']} - {$c}\n"; $i++; } while ($i < 1000001); $diff = (mktime() - $start); echo "With Curlies - Total Time Taken ($diff): ".floor($diff / 60).' mins & '.($diff % 60).' secs'."\n"; $strs = array(); $start = mktime(); $i = 0; do { $c = 'simplicity' + $i; $strs[] = "$t->testvar yadda yadda $a[junk] - $c\n"; $i++; } while ($i < 1000001); $diff = (mktime() - $start); echo "Without Curlies - Total Time Taken ($diff): ".floor($diff / 60).' mins & '.($diff % 60).' secs'."\n";