Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the order of properties inside the Struct changes the size of instance? [duplicate]

I got a struct with the following fields

public struct Person
    {
        public int Age;
        public short Id;
        public byte Marks;
    }

When I initialise it and check the memory size, I get size as 8.

Person instance = new Person {Age = 10, Id = 1,Marks = 75};
Console.WriteLine(Marshal.SizeOf(instance));

However, when I change the order as below and execute it, I get the size as 12.

public struct Person
    {
        public byte Marks;//1 byte
        public int Age;//4
        public short Id;//2
    }

Ideally, it should be 7 bytes. However, from this link msdn I can understand that overhead allocation do happens. However, why is it not consistent? Why the order of properties inside a struct determines the size of its instance?

like image 974
Hunter Avatar asked Oct 20 '22 03:10

Hunter


1 Answers

It is perhaps because of data alignment a.k.a. data structure padding.

E.g. on many 32-bit systems int should be at a memory offset which is some multiple of 4.

From 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.

Perhaps in we have something like this:

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
}
like image 82
AlexD Avatar answered Oct 22 '22 16:10

AlexD