Worst Spatial Locality: Top 3 Code Patterns
Code patterns notorious for destroying spatial locality include random memory access (e.g., poorly distributed hash table lookups), traversing linked lists with scattered nodes, and accessing column-major elements in row-major ordered 2D arrays, leading to significantly higher cache miss rates.
The top 3
- Linked Lists: Up to 10x Slower Than Arrays: Linked lists can be 2-10 times slower than arrays for sequential access patterns due to poor cache performance, as nodes are often scattered across memory, causing frequent cache misses.
- Matrix Traversal: Column-Major 10x Slower in C/C++: Accessing a 2D array column-wise in C/C++ (row-major order) can degrade performance by an order of magnitude or more compared to row-wise access, due to repeated cache misses from non-contiguous memory jumps.
- AoS vs. SoA: Cache Line Waste up to 200%: When using an Array of Structures (AoS) and only accessing a single member, a cache line can load the entire structure, wasting up to 200% of memory for small data types (e.g., 4-byte integer in a 64-bit system with 8-byte pointers), where only a fraction is used. Structure of Arrays (SoA) mitigates this by grouping similar fields, improving spatial locality.
Sources
Open the full topic