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.

Published Wed, Sep 24 2008 1:38 by boban
Filed under: , ,

Comments

# How's it going guys@ Friday, February 05, 2010 9:34 PM

My friend and I were recently discussing about how technology has become so integrated in our day to day lives. Reading this post makes me think back to that discussion we had, and just how inseparable from electronics we have all become.

<br>

I don't mean this in a bad way, of course! Societal concerns aside... I just hope that as memory becomes cheaper, the possibility of downloading our memories onto a digital medium becomes a true reality. It's a fantasy that I dream about almost every day.

<br>

(Posted on Nintendo DS running <a href=www.gather.com/viewArticle.action ds</a> DS NePof)

by bandsxbands

# Great post@ Saturday, February 13, 2010 9:44 AM

Cool blog you got here. I'd like to read something more about that matter. Thnx for giving that information.

by Steave

Leave a Comment

(required) 
(required) 
(optional)
(required)