Bullines
Bullines

Reputation: 5696

What is the memory footprint of an object at Runtime in .NET?

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.

Upvotes: 6

Views: 1108

Answers (5)

Bullines
Bullines

Reputation: 5696

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 
    }
}

Upvotes: 0

Bogdan Maxim
Bogdan Maxim

Reputation: 5946

Try the SOS debugging library. It is the best there is. Articles here and here

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062925

Not without a profiler. It is hard enough just for a single class - see here.

Upvotes: 1

jezell
jezell

Reputation: 2532

Sizeof can be used on value types there is also Marshal.SizeOf which can be used with some hints to .NET:

http://www.pixelicious.net/2008/07/03/exception-trying-to-get-the-size-of-a-c-class-using-marshalsizeof

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.

Upvotes: 3

Brian
Brian

Reputation: 38025

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.

Upvotes: 2

Related Questions