Optimizing for Row/Column-Major Memory Access

Loop interchange reorders nested loops to ensure the innermost loop accesses elements stored contiguously in memory, aligning with the native storage order (e.g., row-major for C/C++, column-major for Fortran) to maximize spatial locality.

The top 3

  1. Cache Lines: The 64-Byte Performance Multiplier: Modern CPUs fetch data in fixed-size 'cache lines,' typically 64 bytes. Accessing data sequentially, aligned with row/column-major order, ensures that an entire cache line is utilized, providing up to 8 elements 'for free' with a single memory transfer and dramatically boosting performance.
  2. Up to 100x Speedup: The Cache Locality Advantage: Optimizing memory access patterns to align with row-major or column-major layouts can lead to dramatic performance improvements, with some benchmarks showing 10x to 100x speedups for large arrays by maximizing cache hits and exploiting spatial locality.
  3. Top 3 Language Defaults: C/C++, Fortran, NumPy: C/C++ and Python's NumPy library predominantly use row-major order (C-contiguous), storing rows contiguously in memory, while Fortran and MATLAB default to column-major order (F-contiguous), storing columns contiguously.

Sources

Open the full topic