Red Stars Programming, food, and rambling

8May/100

PHP string concatenation speed

Something I have always wondered is the speed difference between concatenation strings with in-string variables verses the . operator. I've always assumed . would be much faster, and today I found out.

$amount = 0x1FFFF;
$start = microtime(true);

while ($amount--)
	$throwAway = "this is a test at the $amount point!"; //$throwAway = "this is a test at the ". $amount ." point!";

	echo "Time: ". (microtime(true) - $start);

Exactly as expected, leaving it up to in-string parsing of variables ended up with a bench mark time of 0.1574 and manually concatenating in the variable was 0.1384, which is not a huge difference, but I wanted to see how this would scale when doing multiple concatenations. The string was changed to $throwAway = "this is ". $amount ." a test ". $amount ." at the ". $amount ." point!"; and it's respective in-string.

What I found is that it actually scales to in-string far better! In-string averaged to 0.3235 and manual to 0.3597. After some research it turns out this is because it does a single large concatenation while manually doing it could perform the operation 3 separate times.

Filed under: Web No Comments