C# 内存中对象的大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9324391/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:54:50  来源:igfitidea点击:

Size of object in memory

c#.net

提问by pistacchio

Possible Duplicate:
How to get object size in memory?

可能的重复:
如何获取内存中的对象大小?

Is it possible to know, obviously at runtime, the memory taken by an object? How? Specifically I'd like to know the amount of RAM occupied.

是否有可能在运行时知道对象占用的内存?如何?具体来说,我想知道占用的 RAM 量。

回答by papaiatis

For value types use sizeof(object value)

对于值类型使用 sizeof(object value)

For unmanaged objects use Marshal.SizeOf(object obj)

对于非托管对象使用 Marshal.SizeOf(object obj)

Unfortunately the two above will not get you the sizes of referenced objects.

不幸的是,上面的两个不会让你得到引用对象的大小。

For managed object: There is no direct way to get the size of RAM they use for managed objects, see: http://blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx

对于托管对象:没有直接的方法可以获取它们用于托管对象的 RAM 大小,请参阅:http: //blogs.msdn.com/cbrumme/archive/2003/04/15/51326.aspx

Or alternatives:

或替代方案:

System.GC.GetTotalMemory

System.GC.GetTotalMemory

long StopBytes = 0;
foo myFoo;

long StartBytes = System.GC.GetTotalMemory(true);
myFoo = new foo();
StopBytes = System.GC.GetTotalMemory(true);
GC.KeepAlive(myFoo); // This ensure a reference to object keeps object in memory

MessageBox.Show("Size is " + ((long)(StopBytes - StartBytes)).ToString());

Source: http://blogs.msdn.com/b/mab/archive/2006/04/24/582666.aspx

来源:http: //blogs.msdn.com/b/mab/archive/2006/04/24/582666.aspx

Profiler

探查器

Using a profiler would be the best.

最好使用分析器。

回答by Beatles1692

You can use CLR Profilerto see the allocation size for each type (not a specific object).There are also some commercial products that can help you monitor the usage of memory of your program.JetBrains dotTraceand RedGate Antsare some of them.

您可以使用CLR Profiler查看每种类型(不是特定对象)的分配大小。还有一些商业产品可以帮助您监控程序的内存使用情况。JetBrains dotTrace和 RedGate Ants就是其中的一些。