Tuesday, February 22, 2005

sizeof (.net object) ?

Some time back, I was asked a way to find memory footprint of a dataset and my first thought was, a simple method call that .NET might provide, (No, sizeof operator only works with value types and not reference types) but life is not that eazy, there isn't any magic object that will let me do this.

After some googling found the following piece of code

long bytecount = System.GC.GetTotalMemory(true);
DataSet1 ds = new DataSet1();
ds.EnforceConstraints = false;
ds.Order_Details.BeginLoadData();
ds.Orders.BeginLoadData();
ds.ReadXml("c:\\test.xml");
bytecount = System.GC.GetTotalMemory(true) - bytecount;
MessageBox.Show("Loaded - Waiting. Total K = " + (bytecount/1024).ToString());
long bytecount = System.GC.GetTotalMemory(true);
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load("c:\\test.xml");
bytecount = System.GC.GetTotalMemory(true) - bytecount;
MessageBox.Show("Loaded - Waiting. Total K = " + (bytecount/1024).ToString());

Thanks Barry Gervin, http://objectsharp.com/Blogs/barry/archive/2004/02/24/284.aspx

Thank god, Java developers too, doesn't have a simpler option for this and a solution i found thats used in Java world is much like Barry's code.

Not being skeptical here, but we tried using a memory analysis tool (Compuware's DevPartner) and also used the windows perfmon to cross check the value. Oops, none of the value match, no not some minor differences, it differed by a huge numbers. We had to take a expert guess, one which closely matched the memory size calculated from database columns being fetched, no i am not going to disclose which method was close, as i'm myself not sure which one is.

If you can think of something of perfect way to get the memory foot print of a .NET object, pls let me know with your comments here. I appreciate your help.

No comments: