Interview frequency: …
Short answer
The runtime adds empty bytes (Padding) to align variables to natural memory boundaries; reordering fields from largest to smallest reduces the size of a struct.
Explanation
On 64-bit processors, an 8-byte number must start at an address divisible by 8. For a struct containing byte (1 byte), long (8 bytes), byte (1 byte), the compiler adds 7 padding bytes after the first byte and 7 more at the end, making the total size 24 bytes. Reordering the fields as long, byte, byte reduces the size to 16 bytes, saving millions of bytes in large arrays.
Code example
// Uses 16 bytes instead of 24 due to optimal layout
[StructLayout(LayoutKind.Sequential)]
public struct OptimizedStruct {
public long BigNumber; // 8 bytes
public byte Flag1; // 1 byte
public byte Flag2; // 1 byte
// 6 bytes padding
}Common mistakes
- Ignoring memory alignment when exchanging structures with C libraries through P/Invoke.