Using GZip or Deflate in ASP.NET to improve application performance and conserve bandwith

One of the big complaints about ASP.NET, by proponents of clean semantic mark up, is that the raw html emitted by the ASP.NET engine can be bloated and can, as a result, degrade performance. Of course we could go through all our applications and recode our controls to output cleaner mark up, obviously this takes a lot of time and likely not the choice made by most lead developers when choosing new projects to work on. This article describes a quick method to decrease the size of code sent to browsers and speed up the loading process for users.

GZip and Deflate are compressions used to send data over Http, the majority of browsers now support the decompression of these formats and so they are the best choice for us to use. Developers with direct access to the administration of IIS could of course enable Http Compression (see Here for instructions for setting up IIS). But, if you are using shared hosting or this kind of administration is not feasible, we can use the System.IO.Compression assembly to perform the compression at the application level.

Basically, we add a bit of code to our page load which compresses the output stream of the Response. I tend to put this code in my custom page class in the app_code folder so that it runs automatically for each page, but that may not be suitable for your situation so I will leave this choice up to you.

Obviously, we can’t ignore the fact that some browsers don’t like compressed content, so the first thing we do is to check the Request Headers for the accept encoding header for GZip (most of the major browsers accept both, I have favoured GZip in this snippet as it seems the more popular of the two, but again the choice is yours). Once the allowed compression type is determined the code modifies the Response Filter with the appropriate Stream Compression.

if (Request.Headers["Accept-encoding"] != null && Request.Headers["Accept-encoding"].Contains("gzip"))
Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress, true);
Response.AppendHeader("Content-encoding", "gzip");
else if (Request.Headers["Accept-encoding"] != null && Request.Headers["Accept-encoding"].Contains("deflate"))
Response.Filter = new DeflateStream(Response.Filter, CompressionMode.Compress, true);
Response.AppendHeader("Content-encoding", "deflate");

And thats it! When applied, I saw a noticeable speed up in the page load and on closer inspection in fiddler the size of the documents downloaded had decreased from 16-17Kb to 6Kb in many cases. This is a significant improvement if bandwidth is an issue for you and you can really see how this could make a huge difference to your bandwidth costs and to the performance of your applications.

kick it on