如何获取内存中对象的大小?
我需要知道我的对象在内存中消耗了多少字节(在 C# 中)。 例如我的 Hashtable
、SortedList
或 List
的数量。
I need to know how much bytes my object consumes in memory (in C#). for example how much my Hashtable
, or SortedList
, or List<String>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这可能不准确,但对我来说足够接近了
this may not be accurate but its close enough for me
我认为你不能直接获取它,但有几种方法可以间接找到它。
一种方法是使用 < code>GC.GetTotalMemory 方法来测量创建对象之前和之后使用的内存量。 这并不完美,但只要您控制应用程序的其余部分,您就可以获得您感兴趣的信息。
除此之外,您可以使用探查器来获取信息,或者您可以使用 分析 api 以获取代码中的信息。 但我认为这并不容易使用。
请参阅 了解有多少内存正在被 C# 中的对象使用吗? 对于类似的问题。
I don't think you can get it directly, but there are a few ways to find it indirectly.
One way is to use the
GC.GetTotalMemory
method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.
See Find out how much memory is being used by an object in C#? for a similar question.
非托管对象:
Marshal.SizeOf(object yourObj);
值类型:
sizeof(object val)
托管对象:
https://learn.microsoft.com /en-us/archive/blogs/cbrumme/托管对象的大小
Unmanaged object:
Marshal.SizeOf(object yourObj);
Value Types:
sizeof(object val)
Managed object:
https://learn.microsoft.com/en-us/archive/blogs/cbrumme/size-of-a-managed-object
好的,这个问题已经得到解答,答案已被接受,但有人让我写下我的答案,所以你就可以了。
首先,不能肯定地说。 这是一个内部实现细节,没有记录。 但是,基于包含在其他对象中的对象。 现在,我们如何计算缓存对象的内存需求?
我之前曾在这篇文章中触及过这个主题:
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
以下代码片段应返回传递给它的任何对象的大小(以字节为单位),只要它可以序列化即可。
我从 Quixant 的一位同事那里得到了这个,以解决在游戏平台上写入 SRAM 的问题。 希望它能有所帮助。
感谢并感谢 Carlo Vittuci。
The following code fragment should return the size in bytes of any object passed to it, so long as it can be serialized.
I got this from a colleague at Quixant to resolve a problem of writing to SRAM on a gaming platform. Hope it helps out.
Credit and thanks to Carlo Vittuci.
在调试模式下
加载SOS
并执行dumpheap命令。
In debug mode
load SOS
and execute dumpheap command.