ViewState is the built-in structure for automatically retaining values between multiple requests for the same page in ASP.NET. In other words, ViewState technology saves/restores page state between postbacks. On the other hand, this technology comes with an overhead that affects performance especially during page load since the state data is maintained in a hidden field.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJLTMzMTY4NDI5ZGRrYY+UdQNeb33gRiGcw2LoiMHduA==" />

Reducing ViewState Size

We can completely disable viewstate by setting EnableViewState to false in the page directive but you need extra programming effort for you to take care of the page state. It is a good idea to disable ViewState for the controls that do not actually need it such as Literals and Labels by setting EnableViewState to false. But this do not entirely solve the problem. 

Compressing ViewState

ASP.NET 2.0 comes with the System.IO.Compression namespace, which contains classes with functionality to compress/decompress streams. In ASP.NET 1.1, developers must use third party compression tools such as ICSharpCode.SharpZipLib to compress viewstate.

Compressing/Decompressing using GZipStream

The following class contains two methods for compressing and decompressing a stream.  

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.IO.Compression;

public static class CompressViewState
{
    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 in the App_Code directory.

Utilizing the CompressViewState Class

In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.

The folowing code creates a BasePage class which inherits from System.Web.UI.Page, and web pages using the following Base Page class as the base class utilizes ViewState compression. The BasePage class adds an additional hidden field __COMPRESSEDVIEWSTATE, to store the compressed ViewState.

using System;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Configuration;
using System.Threading;
using System.Globalization;
using System.Text;

public abstract class BasePage : System.Web.UI.Page
{
    private ObjectStateFormatter _formatter =
        new ObjectStateFormatter();

    protected override void
        SavePageStateToPersistenceMedium(object viewState)
    {
        MemoryStream ms = new MemoryStream();
        _formatter.Serialize(ms, viewState);
        byte[] viewStateArray = ms.ToArray();
        ClientScript.RegisterHiddenField("__COMPRESSEDVIEWSTATE",
            Convert.ToBase64String(
            CompressViewState.Compress(viewStateArray)));
    }
    protected override object
        LoadPageStateFromPersistenceMedium()
    {
        string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
        byte[] bytes = Convert.FromBase64String(vsString);
        bytes = CompressViewState.Decompress(bytes);
        return _formatter.Deserialize(
            Convert.ToBase64String(bytes));
    }
}

Demo

Demo project contains two web pages. You may compare the compression performance using the demo project.

Download the viewstate compression demo VS2005 project. 

An online demo web page without viewstate compression.
An online demo web page with viewstate compression.

If you view the HTML of the page with viewstate compression, the __VIEWSTATE field is empty, while our __COMPRESSEDVIEWSTATE field contains the compressed ViewState, encoded in Base64.

ViewState Compression Performance

After few tests using the demo project, ViewState size is reduces by 40 - 60% resulting shorter response times for users and less bandwidth need for site owners.

Compression, decompressing, encoding and decoding data is a quite heavy work for the server so while you are saving from bandwidth and offering shorter response times for users, you are having a performance hit on the server's hardware.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5




Comments

November 15. 2007 21:11

Nice article with even nicer ending. Exactly, compression is a big hit for the server. So my 2 questions:

1. IIS 6.0 compression probably won't help, will it? As I understand viewstate is already "compressed" or hashed so IIS compression won't help in compressing hidden fields data (it will help on other page elements).

2. I think it is better to store viewstate on a server in a session state. That way you save CPU cycles by not compressing it and bandwith by not sending it.

all in all ASP.NET viewstate is extremelly big topic, any addition or research is welcome, but personally I don't think compression is the right way. In some cases we could have 1000 users reading just one page but with 1000 different viewstate's data, even when using cache this would be no win for the server CPU performance when compressing this goodie ;)

steve raynold

November 27. 2007 15:29

Hi,
I implemented your solution, however, it looks like ControlState is no longer working when using the compressed viewstate page.

Kind regards,
Henk

Henk

December 2. 2007 23:51

Thank for doing the hard work for us. I was under the impression that ASP.NET 2.0 already compressed the ViewState, but it clearly does not since this code has reduced my ViewState in one page from 47Kb down to 9kB! Why did Microsoft not compress ViewState by default?

Dave Bartlett

January 18. 2008 10:41

Seams to be a fine thing. But what about server side performance?
In every page request the server executes the compression code.
Couldn't be a problem for the web server performance if your site has very much page impressions?

ltrader

ltrader

February 21. 2008 12:15

doesnt work with wizard control Frown

dom

June 2. 2008 11:31

cool news

senol

June 2. 2008 11:31

cool news

senol

Add comment





(will not be displayed)








  • javascript
  • querystring
  • url parameters
  • parse querystring
  • delayed redirect
  • settimeout
  • focus
  • textbox
  • page load
  • after submit
  • set focus in asp.net 2.0/3.5
  • on page load
  • after postback
  • set control focus
  • postback
  • asp.net 1.x
  • substring
  • substr
  • javascript string methods
  • parsefloat
  • convert strings to numbers
  • parseint
  • javascript history
  • history.go
  • history.back
  • http requests
  • image maps
  • css sprites
  • external css
  • external javascript
  • compress javascript
  • javascript compression
  • ajaxcontroltoolkit
  • tab control
  • array
  • length
  • javascipt
  • lastmodified
  • mstsc
  • terminal services
  • remote desktop connections
  • null
  • undefined
  • array.join
  • string concatenation
  • setinterval
  • clearinterval
  • timing events
  • cleartimeout
  • javascript timing events
  • url redirection
  • location.href
  • location.replace
  • redirect
  • redirection
  • system.io.compression
  • viewstate compression
  • compress viewstate
  • gzipstream
  • loadpagestatefrompersistencemedium
  • savepagestatetopersistencemedium
  • form spam
  • captcha
  • prevent spam without captcha
  • url redirect
  • defaultbutton
  • enter key
  • default button
  • asp.net
  • 2.0
  • form
  • panel
  • 1.1
  • form submit
  • dopostback
  • onkeypress
  • onkeydown
  • onkeyup
  • javascript key events
  • keycode 13
  • disable enter key
  • int32.parse
  • convert.toint32
  • int32.tryparse
  • google
  • hoax
  • gmail
  • storage
  • counter
  • mail
  • visual studio 2005
  • vs 2008
  • copy
  • paste
  • clipboard data
  • static variables
  • application object
  • static property
  • server control
  • web file manager
  • iz web file manager
  • convert
  • parse
  • tryparse
  • file upload control
  • maxrequestlength
  • executiontimeout
  • httpruntime
  • asp.net 2.0
  • registering scripts
  • registerclientscript
  • registerstartupscript
  • cross-browser
  • events
  • improve web site performance
  • compression
  • caching
  • elmah
  • error logging
  • exception
  • error
  • httphandler
  • google sitemap generator
  • sitemap
  • internet information services
  • iis7
  • hosts file
  • localhost
  • windows vista
  • search engine optimization
  • seo
  • search engine friendly pages
  • headscriptmanager
  • class library
  • head
  • css
  • c#
  • iis
  • internet information services manager
  • 401.3 unauthorized
  • 500.0 internal server error
  • http error 500.19
  • google toolbar
  • yellow input fields
  • input
  • select
  • background color
  • mozilla firefox
  • medium trust
  • orcas
  • compileroptions
  • warninglevel
  • zyb
  • mobile phones
  • online backup service
  • online services
  • textarea
  • maxlength
  • limit input length
  • custom server control
  • internal error 2739
  • adobe cs3
  • adobe customer support
  • solution
  • error code 0x80004005
  • 500.19 internal server error
  • meta tags
  • keywords meta tag
  • meta
  • description meta tag
  • fake page rank domains
  • scammers
  • google page rank technology
  • ebay
  • general
  • title
  • page rank