• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

ob_start in foreach loop, how to verify this is correct?

LPH

Well-known member
#1
I'm trying to figure out if there is a good reason to use ob_start within a foreach loop. I'm not sure if there is any performance increase placing the ob_start or whether or not this is placed in the right spot. The ob_start manual examples aren't really helpful.

Here is the code:

PHP:
$forumModel = XenForo_Model::create('XenForo_Model_Forum');
$visitor = XenForo_Visitor::getInstance();
$permissionCombinationId = $visitor['permission_combination_id'];

$threads = XenForo_Model::create('XenForo_Model_Thread')->getModelFromCache('XenForo_Model_Thread')->getThreads(array('discussion_state' => 'visible', 'permissionCombinationId' => $permissionCombinationId), array('limit' => $instance['numberposts']*3, 'order' => 'thread_id', 'orderDirection' => 'desc') );

$i = 0;

foreach ( $threads AS $thread ) {

    ob_start();

    $visitor->setNodePermissions( $thread['node_id'], $thread['node_permission_cache'] );

    if ( $forumModel->canViewForum( $thread ) ) {

        if ( $i == $instance['numberposts']  ) break;

            echo(
                "<div class='entry-meta'><a href='"
                . XenForo_Link::buildPublicLink( 'canonical:threads',
                    $thread )
                . "'>"
                . XenForo_Helper_String::wholeWordTrim( $thread['title'],
                    40 )
                . "</a></div>"
            );

            $i++;

    }

    ob_end_flush();
}
Is ob_start even doing anything? How can I verify? Do I have this in the correct location to improve performance? Does anyone have a good link explaining ways to use ob_start?
 

Jaxel

Well-known member
#4
From my understanding, what ob_start does is send your outputs into the front end, rather than waiting for all the code to finish. Normally, if you do a loop with echos in php, your browser wont actually display any of the echos until the entirety of the code has been executed. What ob_start will do is output the echos to the browser as the code is being executed, instead of waiting till completion.

I wouldn't really know anything about the performance hits, but I haven't really seen any reasons to use ob_start more than once.