Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP HTML generation - using string concatention

A question about different methods of outputting html from PHP; what are the performance differences between these:

Method 1 - variable concatenation

$html = '';
$html .= '<ul>';
for ($k = 1; $k < = 1000; $k++){
    $html .= '<li> This is list item #'.$k.'</li>';
}
$html .= '</ul>';
echo $html;

Method 2 - output buffering

ob_start();
echo '<ul>';
for ($k = 1; $k < = 1000; $k++){
    echo '<li> This is list item #',$k,'</li>';
}
echo '</ul>';

I suspect you get some performance hit from continually modifying and enlarging a variable; is that correct?

Cheers!

Thanks GaryF, but I don't want an answer about architecture - this question is about performance. There seem to be some different opinions / testing about which one is faster, which is why there is not an accepted answer as yet.

like image 481
realcals Avatar asked Dec 14 '22 06:12

realcals


2 Answers

The idea of string concatenation itself aside, you're really asking (I think) how you should be building up web pages, and it strikes me that any form of explicit concatentation is probably the wrong thing to do.

Try using the Model-View-Control pattern to build up your data, and passing it to a simple templating library (like Smarty), and let it worry about how to build your view.

Better separation, fewer concerns.

like image 117
GaryF Avatar answered Dec 28 '22 02:12

GaryF


It's a bit old, but this post by Sara Golemon will probably help. AFAIK the output buffering functions are quite fast and efficient and so is echo, so that's what I would use.

like image 37
too much php Avatar answered Dec 28 '22 03:12

too much php