Measure memory consumption by .NET object
There are many profiling tools like dotTrace (My favorite), CLR Profiler, ANTS, NProf and many others. I use dotTrace regularly, but sometimes I need to measure the size of two objects only, and just to see the difference. I don't wish for such a small operation to start debugging with any tool. So here is what I found very useful:
long memoryStart = 0;
long memoryEnd1 = 0;
long memoryEnd2 = 0;
Thread.MemoryBarrier();
memoryStart = GC.GetTotalMemory(true);
string xmlContent = xDoc.OuterXml;
Thread.MemoryBarrier();
memoryEnd1 = GC.GetTotalMemory(true);
object t = base.FromXml(xDoc);
Thread.MemoryBarrier();
memoryEnd2 = GC.GetTotalMemory(true);
long first = memoryEnd1 - memoryStart;
long second = memoryEnd2 - memoryEnd1;
In my case first one is string(xml content) loaded from xDoc(XmlDocument), and second is some manually(base.FromXml) de-serialized object but you can use any type of object. Most of cases when you want to perform this kind of measure, it is done on the something that is in two different states.
The italic lines are the one that are not important in the sample and are just used to make this code functional.