Click here to Skip to main content
15,860,859 members
Articles / Web Development / IIS
Article

ViewState Compression

Rate me:
Please Sign up or sign in to vote.
4.87/5 (72 votes)
10 Jul 2006CPOL3 min read 364K   162   88
How to compress the ViewState of ASP.NET pages and save bandwidth.

Introduction

Recently, I developed a huge ASP.NET page, with more than 30 controls. As we all know, it's a good idea to disable the ViewState for the controls that don't actually need it, say Literals or Labels. After doing that, I noticed that the hidden ViewState field was still a few KBs big. This is obviously a big problem for the users that still don't have a broadband connection, because uploading 40 KB to the server is really a bad issue, especially when they begin to click the "Submit" button again and again because they don't notice any response. So, after a few searches through the Internet, I built a simple solution to compress the ViewState and therefore save a rough 50% of the bandwidth. This post by Scott Hanselman has been particularly useful. Although it's possible to use external libraries to perform compression tasks, I think the better solution is to use the GZipStream or DeflateStream that the .NET Framework 2.0 includes.

Compressing and Decompressing Data in Memory

First of all, we need a way to compress and decompress an array of bytes in memory. I put together this simple static class that exposes two methods: Compress and Decompress. The two available classes, GZipStream and DeflateStream, according to MSDN, use the same algorithm, so it's irrelevant which one you choose.

The code below is really simple, and doesn't need further explanation:

C#
using System.IO;
using System.IO.Compression;

public static class Compressor {

  public static byte[] Compress(byte[] data) {
    MemoryStream output = new MemoryStream();
    GZipStream gzip = new GZipStream(output, 
                      CompressionMode.Compress, true);
    gzip.Write(data, 0, data.Length);
    gzip.Close();
    return output.ToArray();
  }

  public static byte[] Decompress(byte[] data) {
    MemoryStream input = new MemoryStream();
    input.Write(data, 0, data.Length);
    input.Position = 0;
    GZipStream gzip = new GZipStream(input, 
                      CompressionMode.Decompress, true);
    MemoryStream output = new MemoryStream();
    byte[] buff = new byte[64];
    int read = -1;
    read = gzip.Read(buff, 0, buff.Length);
    while(read > 0) {
      output.Write(buff, 0, read);
      read = gzip.Read(buff, 0, buff.Length);
    }
    gzip.Close();
    return output.ToArray();
  }
}

You need to save this class in a .cs file and put it in the App_Code directory of your ASP.NET application, making sure it's contained in the proper custom namespace (if you don't specify any namespace, the class will be available in the built-in ASP namespace).

Compressing the ViewState

Now, we can actually compress the ViewState of the page. To do that, we have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium. The code simply uses an additional hidden field, __VSTATE, to store the compressed ViewState. As you can see, by viewing the HTML of the page, the __VIEWSTATE field is empty, while our __VSTATE field contains the compressed ViewState, encoded in Base64. Let's see the code.

C#
public partial class MyPage : System.Web.UI.Page {

  protected override object LoadPageStateFromPersistenceMedium() {
    string viewState = Request.Form["__VSTATE"];
    byte[] bytes = Convert.FromBase64String(viewState);
    bytes = Compressor.Decompress(bytes);
    LosFormatter formatter = new LosFormatter();
    return formatter.Deserialize(Convert.ToBase64String(bytes));
  }

  protected override void SavePageStateToPersistenceMedium(object viewState) {
    LosFormatter formatter = new LosFormatter();
    StringWriter writer = new StringWriter();
    formatter.Serialize(writer, viewState);
    string viewStateString = writer.ToString();
    byte[] bytes = Convert.FromBase64String(viewStateString);
    bytes = Compressor.Compress(bytes);
    ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
  }

  // The rest of your code here...
}

In the first method, we just decode from Base64, decompress and deserialize the content of the __VSTATE, and return it to the runtime. In the second method, we perform the opposite operation: serialize, compress, and encode in Base64. The Base64 string is then saved into the __VSTATE hidden field. The LosFormatter object performs the serialization and deserialization tasks.

You may also want to create a new class, for example, CompressedPage, inheriting from System.Web.UI.Page, in which you override the two methods and then inherit your page from that class, for example MyPage : CompressedPage. Just remember that .NET has only single inheritance, and by following this way, you "spend" your only inheritance chance to use the ViewState compression. On the other hand, overriding the two methods in every class is a waste of time, so you have to choose the way that best fits your needs.

Performances and Conclusions

After a few tests, I noticed that the ViewState has been reduced from 38 KB to 17 KB, saving 44%. Supposing you have an average of 1 postback per minute per user, you could save more than 885 MB of bandwidth per month on every single user. That's an excellent result: you save bandwidth (and therefore money), and the user notices a shorter server response time.

I wanted to point out that this solution has a performance hit on the server's hardware. Compressing, decompressing, encoding, and decoding data is quite a heavy work for the server, so you have to balance the number of users with your CPU power and RAM.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Italy Italy
Software Development Manager working on IaaS cloud computing. Cloud believer, (former) entrepreneur, F1 addict.

Follow me at dariosolera.it or on Twitter.

Comments and Discussions

 
GeneralRe: Server Side Pin
Dario Solera18-Jul-06 21:45
Dario Solera18-Jul-06 21:45 
GeneralRe: Server Side Pin
rutgervanhagen4-Jan-07 21:22
rutgervanhagen4-Jan-07 21:22 
GeneralRe: Server Side Pin
Mark Douglas18-Jul-06 22:34
Mark Douglas18-Jul-06 22:34 
GeneralRe: Server Side Pin
Dario Solera18-Jul-06 22:36
Dario Solera18-Jul-06 22:36 
GeneralRe: Server Side Pin
Mark Douglas18-Jul-06 22:41
Mark Douglas18-Jul-06 22:41 
GeneralRe: Server Side Pin
Roger Willcocks19-Jul-06 12:29
Roger Willcocks19-Jul-06 12:29 
GeneralRe: Server Side Pin
Mark Douglas19-Jul-06 21:47
Mark Douglas19-Jul-06 21:47 
GeneralRe: Server Side Pin
Roger Willcocks20-Jul-06 0:49
Roger Willcocks20-Jul-06 0:49 
GeneralRe: Server Side Pin
jonavi18-Jul-06 2:24
jonavi18-Jul-06 2:24 
GeneralRe: Server Side Pin
Dario Solera18-Jul-06 2:29
Dario Solera18-Jul-06 2:29 
QuestionRe: Server Side Pin
jonavi18-Jul-06 6:00
jonavi18-Jul-06 6:00 
AnswerRe: Server Side Pin
Dario Solera18-Jul-06 21:50
Dario Solera18-Jul-06 21:50 
GeneralViewState Pin
Simon Murrell17-Jul-06 6:36
Simon Murrell17-Jul-06 6:36 
GeneralExcellent Article Pin
Krishna Pendoti11-Jul-06 11:14
Krishna Pendoti11-Jul-06 11:14 
GeneralRe: Excellent Article Pin
Dario Solera11-Jul-06 11:20
Dario Solera11-Jul-06 11:20 
GeneralVery nice Pin
WillemM11-Jul-06 4:54
WillemM11-Jul-06 4:54 
GeneralRe: Very nice Pin
Dario Solera11-Jul-06 4:58
Dario Solera11-Jul-06 4:58 
GeneralArticle for ASP.Net 2.0 Pin
DeltaSoft10-Jul-06 20:05
DeltaSoft10-Jul-06 20:05 
GeneralRe: Article for ASP.Net 2.0 [modified] Pin
Dario Solera10-Jul-06 20:58
Dario Solera10-Jul-06 20:58 
AnswerRe: Article for ASP.Net 2.0 Pin
Jasper K.18-Jul-06 22:22
Jasper K.18-Jul-06 22:22 
GeneralConsider HTTP compression Pin
petecooper10-Jul-06 19:35
petecooper10-Jul-06 19:35 
GeneralRe: Consider HTTP compression Pin
Dario Solera10-Jul-06 20:53
Dario Solera10-Jul-06 20:53 
GeneralRe: Consider HTTP compression Pin
petecooper11-Jul-06 4:35
petecooper11-Jul-06 4:35 
GeneralRe: Consider HTTP compression Pin
Daniel Santillanes11-Jul-06 6:30
professionalDaniel Santillanes11-Jul-06 6:30 
GeneralRe: Consider HTTP compression Pin
Dario Solera11-Jul-06 6:36
Dario Solera11-Jul-06 6:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.