hardcore performance tip #1: flush html header early

Output of web applications usually is sent in chunks of data, simply because it’s more effective to send a bulk of data then dribble single bytes through the line. But in some situations, it can be very effective to influence the behaviour of this mechanism.

If you have a page that is expensive to create but not cacheable as a flat file (like search results), it may be a good solution to manually flush the HTTP-output to the user once the head-section of the page is created. That way the browser can already download all the JS and CSS files while the rest of the page is created on the server.

For example, if the content of your page takes 10 seconds to be assembled, the browser can use these 10 seconds to download files – time that otherwise isn’t used for anyting other then waiting.

Headers not flushed

Headers flushed early

The screenshots (from YSlow) show the time the elements of the page need to load. In this example, the result is clearly visible: All header items are already downloaded when the main page has finished.

Of course..

  • .. you can flush your content stream anytime you like, even multiple times if you have more then one expensive part.
  • .. you can flush your headers even for pages that take 500ms to create, especially if your header takes only 1ms.
  • .. there’s a downside:


Depending on your architecture, it may not be the easiest task to flush the current output stream to the browser. Several frameworks and template engines don’t support flushing natively (flush often ends in a higher-ranking template), server filters (compression, manipulation), (reverse-)proxies (content access, CDN) and other layers between the application and the browser may collect content for manipulation and send it in bulk, and with this negating the effect of flushing data.