I do lots of string concatenation in code and then I display output. I was wondering if there is any difference between following two codes:
string concat
$str = '';
for($x =0; $x <= 10000; $x++):
$str .= 'I am string '. $x . "\n";
endforeach;
Output buffering
ob_start();
for($x =0; $x <= 10000; $x++):
echo 'I am string ', $x , "\n";
endforeach;
$str = ob_get_contents();
ob_end_flush();
Here’s a benchmark for you:
My results:
Looks like output buffering +
echois consistently faster, at least in the CLI / on my machine.Brendan Long made a good point in his comment, however — there is such a minor performance difference here that a choice of one or the other is not much of an issue.