Click here to Skip to main content
Click here to Skip to main content

ViewState Compression

, 10 Jul 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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.

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)

Share

About the Author

Dario Solera

Italy Italy
Software Development Manager working on IaaS cloud computing. Cloud believer, (former) entrepreneur, F1 addict.
 
Follow me at dariosolera.it or on Twitter.
Follow on   Twitter   Google+

Comments and Discussions

 
AnswerRe: Memory leak? PinmemberDario Solera7-Jun-08 7:12 
GeneralCompression and Ajax Pinmembermdmasonmbcs14-Apr-08 6:22 
GeneralRe: Compression and Ajax PinmemberTim McCurdy14-Jan-09 3:53 
GeneralRe: Compression and Ajax PinmemberMninawa18-Aug-10 4:25 
GeneralRe: Compression and Ajax PinmemberTim McCurdy18-Aug-10 4:59 
Generalgood stuff Pinmembermrkyle28-Feb-08 19:39 
GeneralExcellent Article..!! PinmemberSujith John Thomas21-Jul-07 3:18 
GeneralAnother way [modified] Pinmemberboros2422-Feb-07 4:13 
Hi, nice code.
I used it but i have some problems with it, (some controls loses the viewstate).
I found a better way apply the same idea:
Create a new class that inherits from PageStatePersister
and overrides the PageStatePersister property of the page.
here is the class i have made:
 
Public Class VSCompressor
    Inherits PageStatePersister
    Private _stateFormatter As LosFormatter
    Protected Shadows ReadOnly Property StateFormatter() As LosFormatter
        Get
            If Me._stateFormatter Is Nothing Then
                Me._stateFormatter = New LosFormatter
            End If
            Return Me._stateFormatter
        End Get
    End Property
    Public Sub New(ByVal page As Page)
        MyBase.New(page)
    End Sub
    Public Overrides Sub Load()
        Dim bytes() As Byte = Convert.FromBase64String(MyBase.Page.Request.Form("__VSTATE"))
        Dim input As New MemoryStream
        input.Write(bytes, 0, bytes.Length)
        input.Position = 0
        Dim gzip As New GZipStream(input, CompressionMode.Decompress, True)
        Dim output As New MemoryStream
        Dim buff(64) As Byte
        Dim read As Integer = -1
        read = gzip.Read(buff, 0, buff.Length)
        While read > 0
            output.Write(buff, 0, read)
            read = gzip.Read(buff, 0, buff.Length)
        End While
        gzip.Close()
        gzip.Dispose()
        Dim p As Pair = DirectCast(StateFormatter.Deserialize(Convert.ToBase64String(output.ToArray)), Pair)
        MyBase.ViewState = p.First
        MyBase.ControlState = p.Second
    End Sub
    Public Overrides Sub Save()
        Dim writer As New StringWriter
        StateFormatter.Serialize(writer, New Pair(MyBase.ViewState, MyBase.ControlState))
        Dim bytes() As Byte = Convert.FromBase64String(writer.ToString)
        Dim output As New MemoryStream
        Dim gzip As New GZipStream(output, CompressionMode.Compress, True)
        gzip.Write(bytes, 0, bytes.Length)
        gzip.Close()
        gzip.Dispose()
        MyBase.Page.ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(output.ToArray))
    End Sub
End Class
 
this is the code you should put in the page:
 
Private _persister As New VSCompressor(Me)
    Protected Overrides ReadOnly Property PageStatePersister() As PageStatePersister
        Get
            Return _persister
        End Get
    End Property
ing it the original size was 900kb
after compress it with your code was 300kb, and now is 150kb

GeneralRe: Another way PinmemberMunsifali Rashid28-Oct-07 12:02 
GeneralRe: Another way PinmemberFahad Azeem25-Apr-08 6:47 
GeneralASP.NET AJAX 1.0 Problem Pinmemberlookaround15-Feb-07 3:48 
GeneralRe: ASP.NET AJAX 1.0 Problem PinmemberDAJG10-Jul-07 9:06 
GeneralRe: ASP.NET AJAX 1.0 Problem Pinmemberuyildir11-Nov-07 11:08 
GeneralRe: ASP.NET AJAX 1.0 Problem PinmemberCoolVini7-Oct-08 0:16 
GeneralRe: ASP.NET AJAX 1.0 Problem Pinmemberkjerolran5-Mar-09 11:02 
GeneralRe: ASP.NET AJAX 1.0 Problem Pinmemberdhejov15-Aug-10 20:39 
GeneralVB.Net version using ICSharpCode.SharpZipLib Pinmemberaka200527-Nov-06 9:26 
Questiondose it make server busy? Pinmemberhuobazi@aspxboy.com25-Nov-06 7:02 
AnswerRe: dose it make server busy? Pinprofessionaladriancs3-Jun-14 21:14 
GeneralExcellent. Pinmemberdeepaks328-Aug-06 22:13 
GeneralServer Side Pinmemberjonavi18-Jul-06 3:08 
GeneralRe: Server Side PinmemberDario Solera18-Jul-06 3:24 
GeneralRe: Server Side Pinmemberjonavi18-Jul-06 3:29 
GeneralRe: Server Side PinmemberDario Solera18-Jul-06 3:36 
GeneralRe: Server Side Pinmemberjonavi18-Jul-06 3:38 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141220.1 | Last Updated 10 Jul 2006
Article Copyright 2006 by Dario Solera
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid