我得到了一个包含以下字段的结构
public struct Person
{
public int Age;
public short Id;
public byte Marks;
}
当我初始化它并检查内存大小时,我得到的大小为 8。
Person instance = new Person {Age = 10, Id = 1,Marks = 75};
Console.WriteLine(Marshal.SizeOf(instance));
但是,当我如下更改顺序并执行它时,我得到的大小为 12。
public struct Person
{
public byte Marks;//1 byte
public int Age;//4
public short Id;//2
}
理想情况下,它应该是 7 个字节。然而,从这个链接 msdn我可以理解开销分配确实发生了。但是,为什么不一致呢?为什么结构内属性的顺序决定了其实例的大小?
这可能是因为数据对齐 a.k.a. 数据结构填充。
例如在许多 32 位系统上,int
的内存偏移量应该是 4 的倍数。
来自 http://en.wikipedia.org/wiki/Data_structure_alignment :
To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
也许我们有这样的东西:
public struct Person
{
public int Age; // 4 bytes
public short Id; // 2 bytes
public byte Marks; // 1 byte + 1 byte for padding
}
public struct Person
{
public byte Marks; // 1 byte + 3 bytes for padding
public int Age; // 4 bytes
public short Id; // 2 bytes + 2 bytes for padding
}