Determine size of object in ViewState
On numerous occasions I've wanted to know how 'big' objects would be in ViewState. For example - imagine you wanted to compare an array of strings to a hashtable or a dataTable. Which would be the most efficient to store in ViewState?
I know that ViewState is optimized for a few primitive types - int, string, bool... even Hashtable and ArrayList. But other than that I've always had to copy/paste the actual __VIEWSTATE value from my Html source and count the characters. Pretty primitive.
Then I stumbled accross a post by Victor Garcia entitled “Don't let the BinaryFormatter get at it!“. It's a great post. Basically objects are serialized to ViewState using the LosFormatter. This formatter is optimized for the above mentioned primitive types.
Now, the topic of this post. How to determine size of object in ViewState? Simply use the LosFormatter in a method like this... And call it with the object you wish to evaluate.
private int GetViewStateSize(object obj)
{
LosFormatter los = new LosFormatter();
StringWriter sw = new StringWriter();
los.Serialize (sw, obj);
int size = sw.GetStringBuilder().ToString().Length;
return size;
}
Thanks, Victor. Be sure to read his post for more info on ViewState and the LosFormatter.