The Size of Structures

Problem
You need to define a structure. You want to know the ideal size and how to optimize it.

Solution
Define structures that are 16 bytes or smaller. Define them so their size is an integer multiple of 4 bytes. Finally, sort their fields so the CLR doesn’t insert hidden padding bytes to keep elements aligned.

Comments
Collections of structures take a block of contiguous memory. You make the best use of memory on a 32-bit OS when you make their size a multiple of 4 bytes. The CLR arranges the layout of all fields in a class to avoid padding bytes. However, it does not perform this optimization on a structure unless it’s marked with the StructLayout attribute set to LayoutKind.Auto.

Example

/* The wrong way to implement a structure.
** It appears to take 8 bytes, but it actually takes 12.
*/
struct ExampleStruct {
    // This is followed by 3 hidden padding bytes.
    public byte aSingleByte;
    public int aSingleInt;
    // This is followed by a hidden padding type.
    public byte aSecondByte;
    public short aSingleShort;
}

/* The correct way to implement a structure.
** No hidden padding bytes are inserted.
*/
struct ExampleStruct {
    public byte aSingleByte;
    public byte aSecondByte;
    public short aSingleShort;
    public int aSingleInt;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s