The impact of Cache Locality
What you'll learn: How the physical layout of memory makes processing arrays in a specific order significantly faster.
The Library Analogy
Imagine you are in a library. If you need ten books that are all sitting next to each other on the same shelf, you can grab them all in one trip. This is efficient. However, if the ten books you need are scattered in different rooms on different floors, you have to walk back and forth for every single book. You spend more time walking than reading.
In your computer, the CPU is the reader, and RAM is the library. Because RAM is relatively slow, the CPU pulls "chunks" of nearby memory into a high-speed storage area called the Cache. If the next piece of data you need is already in the cache, your program flies. If it isn't, the CPU stalls while it waits for a slow delivery from RAM.
Row-Major Order
In C, 2D arrays are stored in "row-major order." This means that even though we visualize an array as a grid, the computer lays it out as one long, continuous line in memory, row by row.
When you access array[0][0] and then array[0][1], the CPU likely already loaded the second value into the cache because they are neighbors. If you jump from array[0][0] to array[1][0], you are jumping over an entire row, potentially missing the cache entirely.
Code Comparison
Notice how these two loops do the exact same work, but the first one respects how memory is laid out:
#define SIZE 10000
int matrix[SIZE][SIZE];
// APPROACH A: Fast (Cache Friendly)
// We move through memory linearly, one neighbor at a time.
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
matrix[i][j] = 0;
}
}
// APPROACH B: Slow (Cache Unfriendly)
// We jump across large gaps in memory for every step.
for (int j = 0; j < SIZE; j++) {
for (int i = 0; i < SIZE; i++) {
matrix[i][j] = 0;
}
}
In Approach A, the inner loop moves through columns within the same row. This is like grabbing adjacent books. In Approach B, the inner loop jumps to the next row every time, forcing the CPU to fetch new data from RAM constantly. On large datasets, Approach A can be 10 to 50 times faster.
Key takeaway
Write your loops to access memory in the order it is stored to keep the CPU fed with high-speed cached data.