PHP Buffer – Give a Boost to Web Page Speed

google-page-speed

Recently, I was in the process of optimizing a web page speed due to Google now ranking websites based on the page load speed. I decided to implement PHP Buffer being the site was entirely php.

PHP output buffering is normally enabled by default. In some older versions of PHP, a string would be sent to your browser every time the interpreter encountered an echo statement or text outside the PHP delimiters.

Output buffering makes this process quicker and more efficient. The buffer is essentially a big memory-resident string. When text is output, it’s appended to the buffer rather than returned to the browser immediately. The buffer is then “flushed”, i.e. its contents are transmitted and the string is reset pending further output. Flushing occurs when:

  1. the PHP interpreter reaches the end of the page
  2. the buffer exceeds the number of bytes specified within PHP’s output_buffering configuration setting, or
  3. the flush() or ob_flush() functions are called

There are a few caveats but, assuming it works within your environment, you should consider flushing the buffer immediately after the page’s </head> tag, e.g.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title>Buffer flushing in action testing</title>
  6. <link rel="stylesheet" type="text/css" href="styles.css" />
  7. <link rel="shortcut icon" href="favicon.ico" />
  8. </head>
  9. <?php
  10. // flush the buffer
  11. flush();
  12. ?>
  13. <body>
  14. &hellip;

(If you’re using WordPress, you could use similar code in your theme’s header.php file.)

Once the browser has received the HTML head, it can begin to download all linked CSS files, favicons and other resources. These downloads can occur while the browser is idle and waiting for the main body content.

The speed increase will depend on the server-side processing required, the weight of your page, the quantity and size of your CSS files, and whether the browser has cached any resources. However, it’s such a simple optimization, there’s little reason not to do it.

I’d be interested to know whether this technique results in a perceivable speed difference on your website or application. Please feel free to comment.