Quiz Entry - updated: 2026.07.07
Your nested loop over a 2D array runs much slower than expected despite simple operations. What should you check first?
Check the loop order: if the inner loop isn't varying the last array index, you're striding through memory and missing the cache on nearly every access.
Diagnosis:
// SLOW - column-major access (cache misses)
for (i=0; i<N; i++)
for (j=0; j<N; j++)
// j changes in inner loop but is first index!
arr[j][i] = ...;
// FAST - row-major access (cache-friendly)
for (j=0; j<N; j++)
for (i=0; i<N; i++)
// i changes in inner loop and is second index
arr[j][i] = ...;
Quick check: Is your inner loop variable the last array index? If not, swap your loops.
Other factors: Working set size (does data fit in cache?), stride length, memory allocation patterns.
Go deeper:
Row- and column-major order (Wikipedia) — how storage order determines which traversal is cache-friendly vs cache-thrashing.
CPU cache (Wikipedia) — cache lines pull in 64 contiguous bytes, so striding across rows wastes most of each line.