tags:

views:

237

answers:

2

What is the easiest way to find out how much memory an object uses in .NET?

Preferably without having to resort to a third party tool. Marshal.SizeOf or the sizeof operator look useful but only work with a restricted range of types.

Some related posts:

+2  A: 

Asked and answered here: Determine how much memory a class uses?

The quick summary is that if you don't want to use a tool, you need to use the .NET Profiling API

The Profiling API is amazingly powerful, but I don't think it would qualify as "easy" by any stretch of the imagination, so I would strongly recommend using a memory profiling tool - there are some free ones that are OK, and some not-too-expensive commercial ones (JetBrains dotTrace in particular) that are really good.

McKenzieG1
A: 

you could also do something like this:

int startMem = GC.GetTotalMemory(true);
YourClass c = new YourClass();
int endMem = GC.GetTotalMemory(true);
int usedMeme = endMem - startMem;
Mladen
I doubt that that is going to work, in the general case. Allocating an object can trigger a new garbage collection cycle, for one thing. Even though you're calling GetTotalMemory(true), someting could be happening in a different thread that effects the result.
Mark Bessey
That is incredibly brittle; in any non-trivial setup you can't guarantee that nothing else is happening. Threading etc...
Marc Gravell
yes you're right. thanx for pointing it out.
Mladen
I don't know...Combine this with checking GC.CollectionCount before and after, and you can at least know if your number is inaccurate. Certainly meets the easy test better than the Profiler API, and will probably work in the 80% case. +1 from me.
Mark Brackett
It looks like this is not possible but Mladen's answer is the closest for all its flaws 8)
Thomas Bratt