Find out how much memory is being used by an object in C#?

user6301 picture user6301 · Sep 13, 2008 · Viewed 12.8k times · Source

Does anyone know of a way to find out how much memory an instance of an object is taking?

For example, if I have an instance of the following object:

TestClass tc = new TestClass();

Is there a way to find out how much memory the instance tc is taking?

The reason for asking, is that although C# has built in memory management, I often run into issues with not clearing an instance of an object (e.g. a List that keeps track of something).

There are couple of reasonably good memory profilers (e.g. ANTS Profiler) but in a multi-threaded environment is pretty hard to figure out what belongs where, even with those tools.

Answer

Alex Duggleby picture Alex Duggleby · Sep 13, 2008

If you are not trying to do it in code itself, which I'm assuming based on your ANTS reference, try taking a look at CLRProfiler (currently v2.0). It's free and if you don't mind the rather simplistic UI, it can provide valuable information. It will give you a in-depth overview of all kinds of stats. I used it a while back as one tool for finding a memory leek.

Download here: http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en

If you do want to do it in code, the CLR has profiling APIs you could use. If you find the information in CLRProfiler, since it uses those APIs, you should be able to do it in code too. More info here: http://msdn.microsoft.com/de-de/magazine/cc300553(en-us).aspx

(It's not as cryptic as using WinDbg, but be prepared to do mighty deep into the CLR.)