Game Development Reference
In-Depth Information
Memory Alignment
The CPU reads and writes memory-aligned data much faster than other data. Any
N-byte data type is memory aligned if the starting address is evenly divisible by N.
For example, a 32-bit integer is memory aligned on a 32-bit architecture if the start-
ing address is 0x04000000. The same 32-bit integer is unaligned if the starting
address is 0x04000002, since the memory address is not evenly divisible by 4 bytes.
You can perform a little experiment in memory alignment and how it affects access
time by using example code like this:
#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)
I wrote a piece of code to perform some operations on the member variables in each
structure. The difference in times is as follows:
Really Slow: 609 ms
Slow: 422 ms
Fast: 406 ms
 
 
Search WWH ::




Custom Search