5. Locality and cache-aware algorithms
One-liner. Performance is often a function of access order, not operation count.
Memorize
- Temporal locality: reuse a value soon. Spatial locality: use neighbours soon.
- Row-major traversal of a matrix matches memory layout; column-major strides across lines and can be 5–10× slower.
- Blocking/tiling processes a matrix in cache-sized tiles so each line is reused before eviction.
- Cache-oblivious algorithms (e.g. recursive matrix multiply) get good locality without knowing cache size.
- Branch prediction is locality too: sorted data makes a branch predictable (the classic "sort first, then sum" trick).
- SIMD rewards contiguous, aligned data; gather/scatter is slower.
- Working set > cache → thrashing even without touching disk.
Trap. Measuring algorithmic complexity only — two O(n²) loops can differ by 10× because of access order. Do this. Benchmark the layout change before changing the algorithm.
Check
Why is row-major traversal of a 2-D array usually faster than column-major in C?
Why
C stores arrays row-major; walking columns strides by the row width and wastes most of every line.