Wednesday, March 25, 2009

Determining an object size in C#

I am implementing business logic for a web application that will result in a sizeable data structure being housed in a class. I may decide to cache the class in the session at some point and I wanted to know how much RAM the class takes up. To figure that out, the best way I could find (here) was to serialize it and determine the size of the resulting binary. Of course the entire class (and any classes it holds as public properties) needs to be serializable.



long lSize = 0;
System.IO.MemoryStream stream = new System.IO.MemoryStream();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter objFormatter =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
objFormatter.Serialize(stream, this.SalesOrder);
lSize = stream.Length;
output.Write("Size of the Object: " + lSize.ToString());