Svish
Svish

Reputation: 158261

C#: Memory usage of an object

Is there a way to find how much memory is used for a particular object? For example a List. Taking everything into account, like string interning and whatever is done by compiler/runtime environment/whatever.

Upvotes: 5

Views: 13149

Answers (4)

Ian Nelson
Ian Nelson

Reputation: 58763

ANTS Memory Profiler profiles the memory consumption of .NET code. I've had great results with it in the past.

Upvotes: 5

Pete Kirkham
Pete Kirkham

Reputation: 49331

This seems to be a sibling of this Delphi question. A naive algorithm won't take into account the difference between aggregation and composition. Even an algorithm based on mark and sweep won't tell you whether a hash table had to grow its internal array because an object was referenced by it. You probably are better off profiling your application for a variety of scenarios and plotting the resource usage against N, where N is some measure of the scale of your dataset.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503140

You'd really have to define exactly what you meant by "how much memory is used for a particular object". For instance, you could mean "if this object were garbage collected, how much would be freed" - or you could mean "how much memory does this object and everything it touches take up."

Your point about string interning is a good example. Suppose you do:

List<string> internedStrings = new List<string>();
List<string> nonInternedStrings = new List<string>();
for (int i=0; i < 1000; i++)
{
    string tmp = new string(' ', i+1);
    nonInternedStrings.Add(tmp);
    tmp = tmp.Intern();
    internedStrings.Add(tmp);
}

Does nonInternedStrings really take up more memory than internedStrings? If internedStrings were garbage collected, it wouldn't free as much memory - but if internedStrings had never been created (including not interning each of its elements) then more memory would never have been required.

If you can be more specific about exactly what you mean, we may be able to help you. It's a complex issue though.

Upvotes: 2

Vyas Bharghava
Vyas Bharghava

Reputation: 6510

Have you tried CLR Profiler 2.0?

Upvotes: 1

Related Questions