Memory Alignment
Learn about memory alignment, which is critical for CPU performance optimization.
We'll cover the following...
Memory alignment and its importance in CPU performance
The CPU reads memory into its registers one word at a time. The word size is 64 bits on a 64-bit architecture, 32 bits on a 32-bit architecture, and so forth. For the CPU to work efficiently when working with different data types, it has restrictions on the addresses where objects of different types are located. Every type in C++ has an alignment requirement that defines the addresses at which an object of a certain type should be located in memory.
If the alignment of a type is 1, it means that the objects of that type can be located at any byte address. If the alignment of a type is 2, it means that the number of bytes between successive allowed addresses is 2. Or to quote the C++ standard:
“An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated.”
We can use alignof
to find out the alignment of a type:
// Possible output is 4std::cout << alignof(int) << '\n';
When we run this code, it outputs 4, which means that the alignment requirement of the type int
is 4 bytes on our platform.
The following figure shows two examples of memory from a system with 64- bit words. The upper row contains three 4-byte integers located on addresses that are 4 bytes aligned. The CPU can load these integers into ...