views:

930

answers:

3

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.

+1  A: 

I have good experiences with MemProfiler. It gives you stack traces of when the object was created and all the graphs of why the object is still not garbage collected.

Lars Truijens
+4  A: 

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.)

AlexDuggleby
+1  A: 

The CLR Profiler, which is provide free by Microsoft does a very good job at this type of thing.

An introduction to the whole profiler can be downloaded here. Also the Patterns & Practices team put something together a while back detailing how to use the profiler.

It does a fairly reasonable job at showing you the different threads and objects created in those threads.

Hope this sheds some light. Happy profiling!

Scott Saad