简体   繁体   English

C#:对象的内存使用情况

[英]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. 例如一个List。 Taking everything into account, like string interning and whatever is done by compiler/runtime environment/whatever. 考虑到所有因素,例如字符串实习以及编译器/运行时环境/无论做什么。

ANTS Memory Profiler profiles the memory consumption of .NET code. ANTS Memory Profiler描述.NET代码的内存消耗。 I've had great results with it in the past. 过去我用它取得了很好的成绩。

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 ? 难道nonInternedStrings真的占用超过内存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. 如果internedStrings被垃圾收集,它就不会释放那么多的内存 - 但是如果internedStrings从未被创建过 (包括没有实现其每个元素),那么就不会需要更多的内存。

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. 您可能最好在各种场景下分析应用程序,并将资源使用情况与N进行绘制,其中N是对数据集规模的一些衡量标准。

你试过CLR Profiler 2.0吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM