Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster: Output buffer or echo

I'm writing a wordpress widget plugin. It should output some html code which should look like this

<a href="link1">link1title</a>
<a href="link2">link2title</a>
<a href="link3">link3title</a>
<a href="link4">link4title</a>
<a href="link5">link5title</a>

I'm running a for loop to output the links and titles from 2 arrays, and I can do that in two different ways:

<?php for ($i = 0; $i < $x; $i++)
    echo '<a href="'.$links[$i].'">'.$titles[$i].'</a>';
?>

Or I can use something like this:

<?php ob_start();
for ($i = 0; $i < $x; $i++) {?>
    <a href="<?php echo $links[$i];?>"><?php echo $titles[$i];?></a>
<?php ob_get_flush();?>

The example is trivial. There is a lot more html code, and a lot more variables involved. Since there is a speed difference between printf and cout in c/c++, I was wondering is there a speed difference between using output buffer and echo.

Also, which one is better to use?

like image 509
Sibin Grasic Avatar asked Apr 24 '26 18:04

Sibin Grasic


1 Answers

Of course there is. With echo, you're dumping to the output stream. With ob_start, you are creating a buffer which must then be processed (the optional argument to ob_start before being dumped to the output stream.

Since the second one is basically "do some stuff, then do the exact same as the first one", it is obvious that it will be slower.

However, if used correctly then the benefits can far outweigh the drawbacks.

like image 66
Niet the Dark Absol Avatar answered Apr 27 '26 07:04

Niet the Dark Absol