Sunday 13 March 2011

HTTP Compression

Ok, so in my last post I said that minimizing the amount of data sent across the wire is a sure way of speeding up performance.

Well, there's a very simple way of doing this which I haven't discussed yet and that's by enabling HTTP compression.

HTTP Compression is a completely lossless way of making your data take up less space. There's two main forms of HTTP compression - GZip and Deflate. These two forms of compression are supported by virtually all of the main browsers now days so what one you choose to use is completely up to you but from my research, GZip seems to be the more popular.

So, how do you enable HTTP compression? Well, there's two ways:
  1. You can do it within IIS (See here for instructions on how to do that: MSDN)
  2. If you don't have access to IIS then you can do it in code using our friend Response.Filter. To do this, just use the following code and place it within your Application_BeginRequest method within your global.asax class:


void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.Headers["Accept-encoding"] != null 
        && 
        Request.Headers["Accept-encoding"].Contains("gzip"))
    {
        Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress, true);
        Response.AppendHeader("Content-encoding", "gzip");
    }
    else if (Request.Headers["Accept-encoding"] != null 
             && 
             Request.Headers["Accept-encoding"].Contains("deflate"))
    {
        Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress, true);
            Response.AppendHeader("Content-encoding", "deflate");
    }
}


So, what we're doing here is, we're checking to make sure that the web browser supports GZip compression and if so, we set up a new GZipStream which will compress our output before sending it out to the client. If the browser doesn't support GZip compression then we fall back to Deflate and check to see if the browser supports that and if so, we use that. If neither is supported then we just send the data back uncompressed.


All very simple so there's no excuse not to use it!

My next post will continue in the same web-optimizing vein, where I'll discuss other, lesser known methods of speeding up performance of web pages.

No comments:

Post a Comment