views:

2843

answers:

4

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.

+1  A: 

Have you tried CLR Profiler 2.0?

Vyas Bharghava
No. Should maybe try that one out. Was hoping for something in code though. So I could sort of Console.WriteLine(MemoryUsageOf(someObject)) or something :p
Svish
CLR Profiler provides you with a wealth of information along memory information... The best way to write code is to write no code at all ;)
Vyas Bharghava
If it would work... Running the program works, launching my program works. But when I exit my program, the CLR Profiler throws an exception:
Svish
+2  A: 

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.

Jon Skeet
well, that is kind of exactly what I wanted to find out :p If, when I fetch a whole bunch of rows from the database (where many rows include the same strings in some columns), should I work on making sure they are interned, or shouldn't I bother with it?
Svish
I would do the simplest thing that works to start with, and then profile your app to see how much memory it uses. I wouldn't use String.Intern though - I've left an answer on your other question to explain why.
Jon Skeet
will check it out, thanks =)
Svish
+1  A: 

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.

Pete Kirkham
+3  A: 

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

Ian Nelson