C#如何查找引用类型的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/862510/
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# How to find the size of a reference type
提问by Doctor Jones
I was wondering if there is a way to find the size of a reference type in C#. I've done some Googling and the general idea on the forums seem to be that this isn't possible. I thought I'd ask you guys and see if anyone here knew better.
我想知道是否有办法在 C# 中找到引用类型的大小。我已经做了一些谷歌搜索,论坛上的总体想法似乎是不可能的。我想我会问你们,看看这里有没有人知道得更好。
After all, profiling tools must have a way of doing this? I know it isn't usual to need to know this information, but it would be useful to have in some situations.
毕竟,分析工具必须有这样做的方法吗?我知道通常不需要知道这些信息,但在某些情况下会很有用。
回答by Lucero
A rough estimate can be done, and tracking the used memory via profilig should also be possible. But the JIT has the freedom of setting up the layout of the type as it fits best, which may also depend on framework version, machine configuration (especially 32bit vs. 64bit), framework provider (MS, Mono, GNU.NET etc.) etc.
可以进行粗略估计,也应该可以通过配置文件跟踪已使用的内存。但是 JIT 可以自由设置最适合的类型布局,这也可能取决于框架版本、机器配置(尤其是 32 位与 64 位)、框架提供者(MS、Mono、GNU.NET 等)等等。
Computing it in advance will be similar to this:
提前计算将类似于:
References are 32bit or 64bit depending on platform
A class instance has an internal reference to the type information (which includes VTable etc.), plus a reference for each reference type contained (including strings or arrays), plus the memory used by any structs (these may be layouted so that access is efficient, in fact leaving some memory unused).
参考是 32 位或 64 位,具体取决于平台
一个类实例有一个对类型信息(包括 VTable 等)的内部引用,加上对包含的每个引用类型(包括字符串或数组)的引用,加上任何结构使用的内存(这些可以被布局,以便访问高效,实际上留下了一些未使用的内存)。
So the question is also, do you want to get the memory used by the class or by the class and the associated data (like strings, arrays, lists, dictionatries etc. in fields)?
所以问题也是,你想获得类使用的内存还是类和相关数据(如字段中的字符串、数组、列表、字典等)?
回答by annakata
Hmmm. I'd be using a profiling tool, but I guess something like this might work:
嗯。我会使用分析工具,但我想这样的事情可能会奏效:
long before = System.GC.GetTotalMemory(true);
Foo instance = new Foo();
long after = System.GC.GetTotalMemory(true);
long consumed = after - before;