如何测量 .NET 中单个对象占用的内存量
我想知道 C#/.NET 和/或 Visual Studio 中是否有一个简单的命令或指令可以告诉我单个对象占用了多少内存?我偷偷怀疑 sizeof() 运算符会对我撒谎……我的这种信念合理吗?
这里有一个有点相关的问题,但没有给出关于如何测量的明确答案一个单独的对象
I'm wondering if there is a simple command or instruction in C#/.NET and/or Visual Studio that can tell me how much memory an individual object is taking up? I have a sneaking suspicion that the sizeof() operator is going to lie to me ... am I justified in this belief?
There is a somewhat related question here, but no definitive answer is given on how to measure an individual object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有确定的方法,因为它对于任何类型的对象来说都不是简单的。
如果该对象包含对其他对象的引用怎么办?如果这些其他对象有其他对象引用它们怎么办?哪个对象实际上拥有该内存空间?是创造它的人还是最后接触它的人?在任何时候它都可能有不同的所有者。或者您只关心引用占用了多少空间?
还有很多问题也问过这个问题......快速搜索就会出现:
如何获取内存中的对象大小?
C#:内存使用情况对象的大小
找出 .net 对象的大小
C#/.NET 对象使用多少内存?
这个清单还在继续......
There is no definitive way because it's not simple for just any type of object.
What if that object contains references to other objects? What if those other objects have other objects referencing them? Which object actually owns that memory space? Is it the one that created it or the last one to touch it? At any one point it could have different owners. Or do you just care about how much space the reference takes?
There is also a ton of questions that have asked this as well... a quick search turns up:
How to get object size in memory?
C#: Memory usage of an object
Find out the size of a .net object
How much memory does a C#/.NET object use?
and the list goes on an on...
没有简单的方法,并且
sizeof
仅适用于值类型。典型的对象包含对列表和其他对象的引用,因此您需要遍历所有指针才能获取实际的字节数,并添加指针大小。您可以查看 .Net Profiling API,或使用 dotTrace 等内存分析器。内存分析器至少可以帮助您查看内存分配的位置以及内存分配是否是应用程序中的问题。这通常比实际对象大小更有用。
There's no easy way and
sizeof
will only be good for value types. A typical object contains references to lists and other objects, so you would need to traverse all pointers in order to get the actual byte count, and add the pointer sizes as well.You can check out the .Net Profiling API, or use a memory profiler like dotTrace. A memory profiler will at least help you to see where memory is allocated and if memory allocation is an issue in your application. This is often more useful than the actual object size.
如果可以的话 - 将其序列化!
If you can - Serialize it!
我想知道 System.Runtime.InteropServices.Marshal.SizeOf() 是如何工作的? Marshal 对象下有许多有趣的静态函数,可能会有所帮助。
I wonder how
System.Runtime.InteropServices.Marshal.SizeOf()
works? There are a lot of interesting static functions under the Marshal object that might be helpful here.