LOGBOOK

HELP

Quiz Entry - updated: 2026.07.07

Why can changing loop order make code 86x faster?

Because the access pattern decides cache behavior: row-major (sequential) access stays in cache, column-major access thrashes it — an enormous speed difference.

Two 4x4 array grids: left, row-major traversal with green arrows sweeping along each row (consecutive memory), labelled roughly 86x faster with few cache misses; right, column-major traversal with red arrows striding down each column, a cache miss on almost every access. C and Java store 2D arrays row by row.

* Walking a 2D array along rows follows how C and Java lay it out in memory, so it hits cache; striding down columns thrashes it. *

Original code (slow):

for (i=0; i<N; i++) {
    for (j=0; j<N; j++) {
        // Column-major access
        sum[j][i] = A[j][i] + B[j][i];
    }
}
// Average runtime: 1,716,543,444

Optimized code (fast):

for (j=0; j<N; j++) {
    for (i=0; i<N; i++) {
        // Row-major access
        sum[j][i] = A[j][i] + B[j][i];
    }
}
// Average runtime: 19,948,247

Speedup: 86x faster!

Why: Arrays are stored row-by-row in memory. Accessing by rows keeps data in cache (spatial locality). Accessing by columns jumps around memory, causing cache misses.

Tip: In C/Java, arrays are row-major. Always iterate with the rightmost index changing fastest: arr[i][j] where j is the inner loop.

Go deeper:

From Quiz: REVE1 / Overview of Computer Systems | Updated: Jul 07, 2026