Override PageStatePersister to Eliminate ViewState
February 24, 2010 2 Comments
I was working on some legacy ASP.Net code recently. We were profiling performance and the key problem was wire performance because of ViewState. Our first idea was to eliminate use of ViewState but there were a lot of implicit dependencies inside of some complex data binding on a GridView control and time was short.
We were able to yield huge performance gains by overriding the PageStatePersister property of a key code-behind class. The change moves the state that would be serialized as great gobs of base64-encoded drek into Session so that it is stored in memory on the server. This isn’t a perfect solution because it increases the memory demand on the server. For this scenario, it was a good medium-term compromise that hugely improves performance over a slow WAN.
The PageStatePersister class and property on System.Web.UI.Page is “new” to ASP.Net 2.0+. It is an abstract class that is exposed as a PageStatePersister property in the code-behind. Microsoft ships two concrete implementations: HiddenFieldPageStatePersister and SessionPageStatePersister. The default is HiddenFieldPageStatePersister which emits base64 text to a hidden __VIEWSTATE input element in the rendered HTML. The SessionStatePersister puts the data in Session instead. It is there to help optimize the generated HTML for mobile browsers and low-bandwidth scenarios.
Here’s the code to do the switcheroo that puts the ViewState data into Session.
/* * HACK: put the veiwstate into session instead of writing to page. Then the __ViewState will only contain the required * ControlState. This increases server memory consumption. A better long-term solution would be to rework the GridView * to work with ViewState disabled and put it inside of an UpdatePanel. */ protected override PageStatePersister PageStatePersister { get { return new SessionPageStatePersister( Page ); } }
Thanks Brian Reiter for the share
Be carefull this could lead to lost of viewstate after few postbacks if you are using multiple tabs