I was reading Game Coding Complete 4th edition. There was a topic regarding Memory alignment. In the code below the author says that first struct is really slow because it is both not bit-aligned nor byte-aligned. The second one is not bit-aligned but byte-aligned. The last one is fast because it's both. He says without pragma, compiler will align the memory itself which causes waste of memory. I couldn't really get the calculations.
This is some portion from the text:-
If the compiler were left to optimize SlowStruct by adding unused bytes, each structure would be 24 bytes instead of just 14. Seven extra bytes are padded after the first char variable, and the remaining bytes are added at the end. This ensures that the entire structure always starts on an 8-byte boundary. That’s about 40 percent of wasted space, all due to a careless ordering of member variables.
This is the concluding line in bolds:-
Don’t let the compiler waste precious memory space. Put some of your brain cells to work and align your own member variables.
Please show me calculations and explain the padding concept more clearly.
Code:-
#pragma pack(push, 1)
struct ReallySlowStruct
{
char c : 6;
__int64 d : 64;
int b : 32;
char a : 8;
};
struct SlowStruct
{
char c;
__int64 d;
int b;
char a;
};
struct FastStruct
{
__int64 d;
__int b;
char a;
char c;
char unused[2];
};
#pragma pack(pop)