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:
Get hands-on with 1400+ tech skills courses.