What’s wrong with ViewState Tokens?
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.
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.
From much of what I read there are only three options:
- Remove ViewStates when they’re not needed.
- Remove any unnecessary elements in the form.
- 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:
More suggestions on compressing the ViewState: