[ Team LiB ] Previous Section Next Section

28.7 Output Buffering

Output buffering is an advanced feature added in PHP 4. Enabling output buffering makes PHP direct the output of applications to a memory buffer instead of sending it directly to the client browser. Once in the buffer, applications can manipulate the output. This manipulation may be compression, conversion from XML to HTML, or even changing embedded URLs. Afterwards, the application emits the processed results to the browser.

Even if you have no need to perform postprocessing on the output your applications emit, output buffering can improve the performance of PHP-based Web sites by decreasing the number of I/O calls to the Web server's infrastructure. Calling the I/O layer of the Web server is typically an expensive operation. Gathering the output into one big block and performing just one I/O operation can be much faster than performing an I/O call every time PHP emits a piece of output—that is, every time you call print or echo.

If your PHP scripts emit HTML pages larger than 10K, allocating and reallocating the buffer can consume more time than is saved from the reduced number of I/O calls. As in many other cases in computer science, you achieve the best performance by finding a good balance between no buffering at all and complete buffering.

Thankfully, PHP's output buffering layer allows users to strike this balance. Instead of telling PHP to buffer all output, you can enable chunked output buffering. Chunked output buffering limits the amount of buffered data to a designated value and flushes the buffer every time the buffer fills up. A good balanced value for chunked output buffering is 4K. It significantly reduces the number of I/O calls your script triggers without consuming significant amounts of memory or imposing noticeable allocation overhead. For instance, if the average size of a PHP-generated HTML page on your site is 50K, PHP will typically perform between 500 and 10,000 I/O calls. With a 4K buffer, it would perform between 12 and 13 I/O calls, resulting in a noticeable gain.

To enable a 4KB output buffer for your entire site, set the output_buffering directive to 4096. If you wish to enable output buffering on a per-script basis, use ob_start. For example, you might write ob_start(null, 4096) to use a 4K buffer.

    [ Team LiB ] Previous Section Next Section