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.
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.
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.
ANTS Memory Profiler profiles the memory consumption of .NET code. I've had great results with it in the past.