Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use ob_get_contents() or $text .= 'test';

I have seen a lot of ob_get_clean() the last while. Typically I have done $test .= 'test'

I'm wondering if one is faster and/or better than the other.

Here is the code using ob_get_clean():

ob_start();

foreach($items as $item) {
    echo '<div>' . $item . '</div>';
}

$test = ob_get_clean();

Here is the code using $test .= 'test':

$test = '';

foreach($items as $item) {
    $test .= '<div>' . $item . '</div>';
}

Which is better?

like image 473
Darryl Hein Avatar asked Nov 15 '08 03:11

Darryl Hein


1 Answers

Output buffers have all the pitfalls of global variables. You have to be aware of all execution paths from the ob_start() to the ob_get_clean(). Are you sure it will get there, and that any buffers opened in between will have been closed? Keep in mind that code can throw exceptions. That can be a really fun bug for the next guy to track down.

On the other hand--and I hate to even mention it--at one time output buffering was somewhat faster at concatenating large strings, for reasons internal to PHP. I'm not sure if that is still true.

like image 77
Preston Avatar answered Sep 28 '22 18:09

Preston