C#:对象的内存使用情况
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/555929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Memory usage of an object
提问by Svish
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.
有没有办法找到特定对象使用了多少内存?例如一个列表。考虑到一切,比如字符串实习以及编译器/运行时环境/任何所做的事情。
采纳答案by Jon Skeet
You'd really have to define exactlywhat 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.
难道nonInternedStrings
真的拿起来比更多的内存internedStrings
?如果internedStrings
被垃圾收集,它就不会释放那么多内存——但如果internedStrings
从来没有被创建(包括不实习它的每个元素),那么就永远不需要更多的内存。
If you can be more specific about exactlywhat you mean, we may be able to help you. It's a complex issue though.
如果你能更多具体究竟你的意思,我们也许能够帮助你。虽然这是一个复杂的问题。
回答by Vyas Bharghava
Have you tried CLR Profiler 2.0?
您是否尝试过 CLR Profiler 2.0?
回答by Pete Kirkham
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.
这似乎是这个Delphi question的兄弟姐妹。天真的算法不会考虑聚合和组合之间的差异。即使基于标记和扫描的算法也不会告诉您哈希表是否必须增长其内部数组,因为它引用了一个对象。您可能最好针对各种场景分析您的应用程序并根据 N 绘制资源使用情况,其中 N 是数据集规模的某种度量。
回答by Ian Nelson
ANTS Memory Profilerprofiles the memory consumption of .NET code. I've had great results with it in the past.
ANTS Memory Profiler分析 .NET 代码的内存消耗。过去我用它取得了很好的结果。