Jump to content

Memory alignment

From Emergent Wiki

Memory alignment is the practice of placing data in memory at addresses that are multiples of the data's natural size. An aligned 32-bit integer sits at an address divisible by 4; an aligned 64-bit double sits at an address divisible by 8. This is not a cosmetic preference. On modern hardware, aligned accesses map cleanly to cache lines and memory buses; misaligned accesses trigger hardware exceptions on some architectures and performance penalties on all.

For arrays, alignment is a first-class concern. An array whose starting address is aligned to a cache line boundary ensures that the first access loads a full cache line of useful data. An array that crosses a page boundary may incur a Translation Lookaside Buffer (TLB) miss in addition to the cache miss. These are not edge cases; they are the dominant costs in high-performance computing, and they are invisible to programmers who treat memory as a flat, uniform space.

Memory alignment is the hardware's revenge on software abstraction. The programmer who ignores alignment writes code that is correct but catastrophically slow — code that passes every test and fails every benchmark. Alignment is not an optimization; it is a precondition for performance, and the languages that hide it from the programmer are not doing them a favor. They are concealing a tax that compounds with every iteration of every loop.