Memory Alignment
Explore the concept of memory alignment in C++ and its impact on CPU efficiency. Understand platform alignment requirements, how to check and enforce alignment using standard functions, and how to allocate aligned memory on the heap. Learn to apply alignas for custom alignment to optimize cache usage and improve overall program performance.
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:
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 ...