问题描述
有一个与.NET对象相关的固定开销,如本SO问题所述:根据您是32位还是64位进程,.NET对象的内存开销是12字节还是24字节?
There is a fixed overhead associated with a .NET object as more fully outlined in this SO question: What is the memory overhead of a .NET Object being 12 or 24 bytes depending on whether you are in a 32 bit or 64 bit process.
也就是说,基本值类型(如 int,double,boolean
等)不会产生开销,因为它们是 Value Types .
That said, basic value types like int, double, boolean
, etc incur no overhead because they are Value Types.
在哪里保留了您在应用程序中放在一起的自定义 struct
类型?一方面,它们是上面的 int,double,boolean
之类的值类型[因此不应该产生开销],但是另一方面,它们是间接地从 System.Object
和所以应该(从技术上)产生开销.
Where does that leave custom struct
types that you put together in your application? On the one hand, they are value types like int, double, boolean
above [so should not incur overhead] but on the other hand they derive indirectly from System.Object
and so should (technically) incur overhead.
推荐答案
它们与原始类型没有什么不同.除了所拥有的字段外,它们不承担额外的开销.它们源自 object
的事实并不意味着它们会产生引用类型所带来的开销,即方法表指针和同步根块.
They are no different than primitive types. They carry no additional overhead other than the fields they have. The fact that they derive from object
doesn't mean they incur the overhead that reference types carry, which is the method table pointer and sync root block.
您可以使用 Marshal.SizeOf
:
You can test this out using Marshal.SizeOf
:
void Main()
{
var f = new Foo();
Console.WriteLine(Marshal.SizeOf(f));
}
public struct Foo
{
public int X { get; set; }
public int Y { get; set; }
}
这将在32位模式下打印8,这恰好是两个整数值(每个4字节).
This will print 8 in a 32bit mode, which is exactly two integer values (4 bytes each).
注意 Marshal.SizeOf
将输出非托管对象的大小.CLR仍然可以自由地对字段进行重新排序或将它们打包在一起.
Note Marshal.SizeOf
will output the size of the unmanaged object. The CLR is still free to re-order fields or pack them together.
这篇关于.NET自定义结构类型的内存开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!