I have a static object at runtime that is basically a list of other objects (ints, strings, Dictionary, other objects, etc). Is there way to determine the memory used by my static "list of other objects" object at runtime? This would be handy for instrumentation and reporting purposes.
5 Answers
Sizeof can be used on value types there is also Marshal.SizeOf which can be used with some hints to .NET:
But... that isn't exactly the total cost since the runtime does allocate extra bytes for classes for things like sync blocks.
If you are really interested in measuring this type of thing, however, you should use the profiling API:
http://msdn.microsoft.com/en-us/library/ms404386.aspx
Or a free tool like windbg that can do all sorts of wonderful things.

- 2,532
- 14
- 12
You are probably asking for something you could call from your code (which I would like to know too), but I felt I should mention Ants profiler [http://www.red-gate.com/Products/ants_profiler/index.htm] in case others aren't looking for something as specific. It will tell you all kinds of information about your code while it's executing including how much memory is being used.
From their website...
Profile memory to understand how your application uses memory, and to locate memory leaks. The memory profiler allows you to take snapshots at any point in the execution of your program, so you can see what memory is in use at that point. You can take multiple snapshots at different times while your application is running, so you can compare application memory states.

- 37,399
- 24
- 94
- 109
-
I am indeed looking for a programmatic implementation. But I agree that the ANTS Profiler can definitely be handy in the right situations :) – Bullines Oct 21 '08 at 20:38
Not without a profiler. It is hard enough just for a single class - see here.

- 1
- 1

- 1,026,079
- 266
- 2,566
- 2,900
Thanks for the replies. I think my initial plan of attack, because I'm sure most of the objects will be serializable, will be something like this:
using (MemoryStream memstream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(memstream, myObjectOfObjects);
mem_footprint += memstream.Length;
}
catch
{
// not a serializable object
}
}

- 5,626
- 6
- 53
- 93