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.
getsizeof() function can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.
Object references consume 4 bytes. boolean and byte values consume 1 byte. short and char values consume 2 bytes. int and float values consume 4 bytes.
A single object may use 2, 4, 8, or even more consecutive memory addresses. The amount of memory that an object uses is based on its data type.
One way is to use the GC. GetTotalMemory method to measure the amount of memory used before and after creating your object.
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: https://github.com/MicrosoftArchive/clrprofiler
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.)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With