Rasmus on Interpolation vs. Concatenation
Rasmus Lerdorf has been tweeting this morning about concatenation vs. interpolation in PHP. Micro-optimizations to be sure, but an interesting look under the hood.
Question from a colleague: Should we use 1. "abc $a def" or 2. 'abc '.$a.' def' ? Answer next tweet #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
It's a toss-up. 1. Takes an extra opcode, but 2. creates more tmpvars. Performance is similar. #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
And no, for those who asked, "{$a}" makes no difference. Same generated opcodes. #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
And yes, the more variables you have, the slower option 2 becomes because each concat creates another tmpvar. #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
sprintf() for lots of variables is about the same speed as concatenation, but not as fast as interpolation. #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
Bear in mind that these are micro-optimizations. If you have even a single SQL/memcache lookup, there is no point worrying about this. #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
Someone asked about Heredoc. Heredoc is just another syntax for interpolation. Identical opcodes, so identical (opcode cached) perf #php
— Rasmus Lerdorf (@rasmus) May 30, 2012
If you want to examine the opcodes yourself, you can use vld, the Vulcan Logic Disassembler.