ViewState Tokens and Performance Tips – LoadStorm

ViewState tokens are a common performance issue I come across while helping customers due to the size of these tokens. I’ve found some information about performance improvements, but I have not tested any them.

What is a ViewState token? It is ASP.NET’s way to ensure the state of the page elements sent to a browser match what the browser sends back. It is an encoded string sent out to the user which gets sent back to your server in a POST request. The main problem with this kind of token is that it needs to represent every form element on the page. This gets large when complex elements such as a drop-down menu is in the form. Countries, companies, customers, or other database tables with many entries are good drop-down examples. In some cases it can double the size of your page. The largest ViewState I’ve seen was 300,000 characters long. The generated HTML for that page was at least 600,000 characters. That’s a lot of response text since almost half was just the token.

Performance Impacts

As the ViewState grows larger. It affects performance in the following ways:

  • Increased CPU cycles to serialize and to deserialize the ViewState.
  • Pages take longer to download because they are larger.
  • Large ViewStates can impact the efficiency of garbage collection.

According to one source I found:

ViewStates work best when serializing basic types such as strings, integers, and Booleans. Objects such as arrays, ArrayLists, and Hashtables are also good with those basic types. When you want to store a non-basic type, ASP.NET tries to use the associated type converter. If it cannot find one, it uses the expensive binary serializer. The size of the object is proportional to the size of the ViewState. Avoid storing large objects.

Improvement Options

From much of what I read there are only three options:

  1. Remove ViewStates when they’re not needed.
  2. Remove any unnecessary elements in the form.
  3. Compress the ViewState to reduce the data transferred.

I rarely see ViewStates used that are not needed, and in some cases a few elements can be removed from the form. Compression is often the best improvement for the end-user experience. Keep in mind that compressing and decompressing the ViewState causes more CPU work. This could have a poor impact on performance at scale.

Compress a ViewState whenever it is above a particular size:
http://sebnilsson.com/3ec8d9da/asp-net-webforms-seo-compressing-view-state/

More suggestions on compressing the ViewState:
http://stackoverflow.com/questions/2380106/asp-net-compress-viewstate
http://www.codeproject.com/Articles/14733/ViewState-Compression

Sources:

https://msdn.microsoft.com/en-us/library/ff647787.aspx#scalenetchapt06_topic19
http://www.monitis.com/blog/2012/07/26/improving-asp-net-performance-part-12-view-state-management/
http://jagbarcelo.blogspot.com/2009/03/viewstate-size-minimization.html

Similar Posts