As a coder who picked up on Java and JavaScript string concatenation ("text" + var + "more text"), in PHP I always used "text" . $var . "more text". That may change soon, though, as it seems that embedding variables in string literals is a bit faster.

To test it, I ran this basic stress test (PHP 5.3.13) with $iters = 1000000:

$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
    $x = /* The test */;
}
print (microtime(true) - $time); print " - <Result type>\\n";

The result was a bit surprising:

0.28899502754211 - One literal // $x = "a b c";
0.36314988136292 - Concat literals // $x = "a " . "b" . " c";
0.37605690956116 - Concat var // $x = "a " . $b . " c";
0.34101295471191 - Var in literal // $x = "a $b c";
0.34043002128601 - Var braced in literal // $x = "a {$b} c";
0.37888598442078 - Concat single-quoted var // $x = 'a ' . $b . ' c';

I re-ran the stress test several times, and achieved similar results almost every time. Embedding {$b} or simply $b (where possible) seems to be the fastest way of inserting a variable into a string. Concatenation with single-quoted strings, however, seems to be the slowest. Surprisingly, concatenating string literals is not properly optimized, so it's only slightly faster than concatenating with a variable.

Happy string constructing!

Next Post Previous Post