How Viewstate does affect performance? Remember that Client and Server Communicates via a postback. And posting a web page as large as 50KB is like uploading a file on youtube or attaching a file on yahoo mail, imagine that. You can check how large is your viewstate when you look at the rendered page by clicking View Source for IE, the part that is garbage looking that occupies almost the whole part of your notepad. Just look at the tag saying __VIEWSTATE.
What really is the function of viewstate? Viewstate is used by ASP.Net to remember the state of the control before a postback occur. One good example is how ASP.Net know that a text has changed when a postback occur or if you have enabled autopostback of the control. It is very simple with the use of viewstate, the value of the textbox is saved on the viewstate, when user changes the value of it and a postback occurs it compares the new value of the textbox and the viewstate if it matches if it does not it raises onChange event.
Now imagine how many controls you have and all of them have viewstate. Each control occupies at list 20 bytes multiply it by the number of your controls. Aside from those, templated and bounded controls like Gridview, Datalist or dropdownlist occupies a very large size of viewstate. But wait we cannot just disable all of them or put enableViewState = false on page directives. What we can do is to use Viewstate wisely.
Here are some pointers I think would help you decide when to disable viewstate.
- Dynamically inserted value on the controls (By binding or programmatically assigning) – The values of this controls will not retain when it is rerendered, e.g. Switching from view1 to view2. But you have to consider two things, if you think repopulating the values for every render is to heavy to implement then don’t disable the viewstate, if not then you may disable it and reinitialize your controls on render event. Why am I suggesting this? It’s because processing serverside code is much faster than transferring a large junk of data back to the server and unto the client on roundtrips.
- On Datalist and DropDownList – If you are not using the OnSelectedIndex Change event then you may disable the viewstate.
- On Gridviews – This is the hardest part to decide whether to disable viewstate or retain it. If you are just displaying data on it or even using it just for selection, then disable the viewstate. If you are using paging, edit or delete functionality then don’t. Gridview has the largest viewstate capacity so you should use it wisely. If you have to update as many as 5 columns then why not just open another view then set the values there to be updated rather than updating it on the gridview directly.
These are just some of my tips, but you should always test the effect of it so you can see if controls behaves as expected even without viewstate.