C# 如何查找引用类型的大小
我想知道是否有办法在 C# 中查找引用类型的大小。 我做了一些谷歌搜索,论坛上的总体想法似乎是这是不可能的。 我想我应该问问你们,看看这里是否有人更了解。
毕竟,分析工具必须有办法做到这一点? 我知道通常不需要了解这些信息,但在某些情况下了解这些信息会很有用。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯。 我会使用分析工具,但我想这样的东西可能会起作用:
Hmmm. I'd be using a profiling tool, but I guess something like this might work:
可以进行粗略的估计,并且也应该可以通过配置文件跟踪已使用的内存。 但是 JIT 可以自由地设置最适合的类型布局,这也可能取决于框架版本、机器配置(尤其是 32 位与 64 位)、框架提供商(MS、Mono、GNU.NET 等) 引用是 32 位或 64位
提前计算将类似于:
引用是 32 位或 64 位,具体取决于平台
类实例具有对类型信息的内部引用(其中包括 VTable 等),加上所包含的每个引用类型的引用(包括字符串或数组),加上任何结构使用的内存(可以对这些结构进行布局,以便访问高效,实际上留下一些未使用的内存)。
所以问题也是,您是否想要获取类使用的内存或类以及关联的数据(如字段中的字符串、数组、列表、字典等)?
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.
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).
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)?