C#:对象的内存使用情况 [英] C#: Memory usage of an object

查看:84
本文介绍了C#:对象的内存使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以找到特定对象使用了多少内存?例如一个列表.考虑到所有因素,例如字符串实习以及任何由编译器/运行时环境/执行的操作.

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);
}

nonInternedStrings是否真的比internedStrings占用更多的内存?如果internedStrings被垃圾回收,它不会释放那么多内存-但是如果>从未被创建过 (包括不对每个元素进行内插),那么就不再需要更多的内存了.

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.

这篇关于C#:对象的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆