Disable ViewState - reap performance gains
October 19, 2008 at 11:17 AM
Turning off viewstate for an entire page or just for certain controls can potentially reduce bandwidth greatly. This is not news for most developers, but at least for me, I often forget to take this into account when developing ASP.NET pages.
Just the other day, I found two server side controls that had enough content in them to make viewstate much larger than it should have been. After disabling viewstate on those 2 controls, the viewstate hidden field sent to the client went down from about 6,500 bytes to 500 bytes! That's 6 KB of unneeded data that was being sent down to each client. And because viewstate is sent to the client in a hidden input field, if there's a postback, all that data gets sent back up to the server. Most people don't have a very fast upload speed, so the post hurts performance more than sending the data to the client.
Especially for pages that don't do any postbacks, there's no reason I can think of to even have viewstate turned on at all. For these pages, disable viewstate at the page level. It's scary to imagine the number of ASP.NET pages out there that output static reports in large tables (gridview, datagrid, listview etc) with viewstate unnecessarily enabled. Bandwidth savings on such pages could probably be as large as the tens or even hundreds of kilobytes.
There are reasons to leave viewstate enabled for server controls on pages that do postbacks, however. During a postback, if the resources required are high for obtaining the data needed to put back into a disabled viewstate control, it may be more advantageous to leave viewstate enabled. For instance, if you need to make a database call or consume a web service across a network to obtain the data, leaving viewstate turned on may be better. Same with most standard form controls (e.g. input, select), there's typically not going to be enough of a performance gain to justify turning off viewstate and losing some of the perks you get with viewstate enabled when a page is going back and forth between the client and server one or more times. The big performance gains are going to be with server controls that output large blocks of HTML not editable by the user.