System Design · Concept Library · Free article
Why Memory Access Patterns Matter
Sum the same grid with two loops. Follow each read to see why one order reuses cache lines and another keeps fetching them.
A CPU cache keeps copies of recently accessed memory in cache lines. Accessing nearby bytes soon after a fill uses spatial locality; revisiting data before eviction uses temporal locality. Access order and the active working set determine whether useful data remains cached. Two programs can read the same bytes and do the same arithmetic while causing different memory traffic.
The task: add every cell of a grid
You have probably solved a problem that asks for the sum of a matrix. Consider a 4 × 4 grid containing the values 1 through 16, written row by row. Add every cell once and the answer is 136. You can visit each row from left to right, or each column from top to bottom. Both versions perform sixteen reads and sixteen additions. In DSA terms, both take O(rows × columns) time and O(1) extra space.
Yet the order can change how often the CPU has to fetch data from farther away. Big-O describes how work grows with input size. It does not count every memory transfer hidden behind an array access. This lesson follows that familiar inner-loop read all the way to the cache. First we need to understand what the cache holds.
A load can be served close to the CPU
Your array lives in the program’s memory. When an instruction needs a cell, the processor issues a load: a request to read the value at its address. A register holds the operand used by an instruction. A CPU cache keeps a small collection of memory copies close to the execution hardware, so many loads can be served without reaching RAM. You do not normally write an explicit cache lookup for each array access; hardware manages it.
Creating an array and keeping it alive are separate from keeping its data in cache. The previous memory lesson explains allocation and lifetime. Here the grid stays valid for the whole calculation. We are asking where each valid read gets its value, not whether its storage still exists.
| Place | Role | Question to ask |
|---|---|---|
| Registers | Values directly used by instructions | Which operands are ready? |
| CPU caches | Small stores of copied memory lines near execution | Is the needed line present at this level? |
| Main memory (RAM) | Larger working storage for running programs | Must this request reach memory? |
| Persistent storage | Files and other durable data | Does software or paging need storage I/O? |
A cache hit finds the requested data in the cache being checked. A cache miss does not. In a machine with several cache levels, a miss in the first level may hit in another. A last-level miss may reach main memory. A CPU cache miss does not by itself mean a disk read.
The cache is smaller than RAM, so it cannot retain every line indefinitely. On a miss it may need to fetch a line and replace another. That replacement is an eviction. In this read-only lesson, eviction discards a cached copy; the source bytes remain in RAM. Stores need additional rules, such as what happens to modified data, which this model does not implement.
The hierarchy trades capacity and access cost. Physical latencies depend on the processor, memory system and competing work. Our single-cache machine uses declared teaching costs so the experiment remains inspectable. Cornell’s cache notes explain cache hits, misses, locality and multiple levels.
A grid in code becomes a sequence of addresses
A matrix looks two-dimensional on paper, but our example stores its cells in one contiguous sequence, row after row. This is row-major layout. To keep the diagram small, every cell is a one-byte unsigned value and the grid starts at aligned address 0. Values 1 to 16 all fit in a byte. The running total uses a separate, wider accumulator; it does not wrap at 255.
The first row has values 1, 2, 3, 4 at addresses 0, 1, 2, 3. The second row has values 5, 6, 7, 8 at addresses 4, 5, 6, 7. A value and its address are different: value 5 is stored at address 4. In this specific grid, address = row × 4 + column, using zero-based indices.
For an element size of E bytes and C columns, the more general formula is base + (row × C + column) × E. An array of 4-byte integers therefore has different byte offsets. A list of references to separately allocated rows may not be one contiguous rectangle at all. We declare the representation instead of assuming every language stores a nested array the same way.
total = 0 // wide enough for the sum
for row in 0..3:
for column in 0..3:
total += grid[row * 4 + column]
return total // 136One miss brings a line, not just the requested byte
A cache line is a fixed-size block transferred and tracked together by a cache. With four-byte aligned lines, addresses 0 to 3 share line 0; 4 to 7 share line 1; 8 to 11 share line 2. Compute the line number as floor(address / line size). Reading address 2 on a cold cache fetches the line containing bytes 0, 1, 2 and 3.
If the next read asks for byte 3 while that line remains cached, no new fill is needed. This is spatial locality: using nearby locations close together in time. If the next read asks for byte 2 again, it can reuse the same cached value. This is temporal locality: reusing a location before it has been displaced. Neither kind of reuse is guaranteed just because an address appears somewhere later in the program.
The lab uses tiny lines of 2, 4 or 8 bytes to keep each byte visible. Those sizes are teaching choices. Do not infer your machine’s cache-line size from this diagram. The arithmetic for grouping addresses applies to a chosen line size; the size and other policies must come from the target hardware.
With one-byte grid cells, four-byte lines and two cache slots, row-first traversal needs 4 fills while column-first traversal needs 16. Both visit each cell once and total 136. Grouping repeated reads can retain the same answer with fewer fills. Enable JavaScript to step through the cache.
Step through the first four reads. Reading value 1 at address 0 brings the first row’s four bytes into the cache. Values 2, 3 and 4 are already in that same line when their turns arrive. The small example lets one row equal one line; a larger real row usually spans many lines. Notice that the RAM grid never disappears when its cache copy changes.
What changes when you swap the loops?
Keep the same grid and the same addition. Put the column loop outside and the row loop inside. Now the first four values read are 1, 5, 9 and 13, at addresses 0, 4, 8 and 12. Each comes from a different row line. After that, value 2 sends us back to the first row.
The stride is the distance between successive addresses in a regular part of the traversal. Inside our row-first loop it is one byte; inside the column-first loop it is four bytes. A larger stride can use fewer neighbors from each fill before moving away. It is the resulting line sequence and retention that matter, not the word “column” by itself.
total = 0
for row in 0..3:
for column in 0..3:
total += grid[row * 4 + column]
return total // 136
// First addresses: 0, 1, 2, 3total = 0
for column in 0..3:
for row in 0..3:
total += grid[row * 4 + column]
return total // 136
// First addresses: 0, 4, 8, 12With one-byte grid cells, four-byte lines and two cache slots, row-first traversal needs 4 fills while column-first traversal needs 16. Both visit each cell once and total 136. Grouping repeated reads can retain the same answer with fewer fills. Enable JavaScript to step through the cache.
Compare Rows first with Columns first. Both start cold, meaning no grid lines are cached yet, and both have room for just two lines. Step far enough to revisit the first row. In column order its cached copy has already been replaced. The sum is still correct; the machine has to fetch that row again.
Account for every fill
For sequential order, reading byte 0 fills line 0. Reads 1, 2 and 3 hit it. Byte 4 fills line 1, followed by three more hits. The same pattern holds for lines 2 and 3. There are four misses and twelve hits, fetching 4 × 4 = 16 bytes in total. Every fetched byte is used before its line is displaced.
For column order, the first four addresses touch lines 0, 1, 2 and 3. The cache has only two slots. By the time address 1 needs line 0 again, the first line has been evicted. The repeating line sequence is 0, 1, 2, 3, four times. Every read misses, so sixteen fills transfer 64 bytes even though the workload uses only sixteen distinct bytes.
The cache is fully associative: any line may occupy any slot. Its replacement policy is least recently used, or LRU. Every access makes its line the most recent; a miss into a full cache evicts the line whose last access was longest ago. The diagram orders slots by recency, not by physical wiring. This avoids confusing a line’s current position in the display with a fixed hardware location.
| Order | Hits | Misses | Fetched bytes | Teaching ticks | Checksum |
|---|---|---|---|---|---|
| Nearby bytes | 12 | 4 | 16 | 52 | 136 |
| Columns first | 0 | 16 | 64 | 160 | 136 |
A hit costs one teaching tick. A miss costs ten total: one lookup tick plus nine fill ticks. The sequential trace therefore costs 12 × 1 + 4 × 10 = 52 ticks; the column trace costs 16 × 10 = 160. The model completes one blocking read before starting the next. It does not overlap outstanding requests.
The checksum supplies one useful sanity check, but it is not sufficient evidence of equal work. Addresses 0 and 3 have the same value sum as 1 and 2. Our two presets have a stronger property: each visits exactly the same sixteen addresses once, and all reads use immutable values. For these integer sums, changing their order preserves the result.
Repeated access helps only if the lines survive
The working set here is the collection of cache lines needed during the interval in which the program expects to reuse them. It is not necessarily the program’s total allocated memory. A large allocation can be scanned a small region at a time; a small but scattered set of objects can touch many lines.
Suppose a second version of our grid task adds selected cells repeatedly. Addresses 0, 4, 0, 4, 0, 4 need two lines. In a two-slot cache, the first two reads miss and the remaining four hit. Now select three cells instead: 0, 4, 8, 0, 4, 8. The three-line cycle does not fit, and every read misses under LRU. Increase the cache to three slots and the second pass hits all three.
For the sixteen-byte column traversal, four cache slots retain all four lines. Only the first access to each line misses. Both traversal orders then have four misses, twelve hits and the same modeled time. That negative control matters: an access pattern is costly relative to a cache configuration, not inherently slow under every possible machine.
Real caches are often set associative: a line can use only a subset of the slots. Lines can compete for those slots even when the cache has unused capacity elsewhere. The lab has no such mapping conflicts. Hardware may also use a replacement approximation instead of exact LRU.
With one-byte grid cells, four-byte lines and two cache slots, row-first traversal needs 4 fills while column-first traversal needs 16. Both visit each cell once and total 136. Grouping repeated reads can retain the same answer with fewer fills. Enable JavaScript to step through the cache.
Group each pair changes those six reads to 0, 0, 4, 4, 8, 8. The values are 1, 1, 5, 5, 9, 9, totaling 30. Each second read is a hit, so there are three misses instead of six. We preserved each cell’s two contributions, and used temporal locality to keep the second read close to the first. This reorder is valid for our exact integer sum. It would need a separate correctness argument if each read depended on a previous update.
Do both passes while a small region is still cached
Now change the task to add every grid cell twice, while keeping all 32 reads. Two full row-first scans total 272. With two cache slots, the first scan ends holding the last two rows. Starting the second scan fills the first rows again and displaces the remaining ones before their reuse. The two scans cause eight misses.
Instead, scan the first row twice, then the second row twice, and so on. Each row needs one fill, then both passes use it before moving on. The total remains 272, but only four fills are needed. This is a small example of blocking, also called tiling: complete the reusable work on a bounded region before advancing. We keep the redundant reads deliberately so that the experiment isolates locality; a real optimizer might simplify the arithmetic for this particular sum.
For matrix multiplication or image processing, a tile can support several useful calculations before it leaves cache. Count all data needed at once, including input regions, outputs and temporary storage. A tile that is too large loses the intended reuse. Loop changes must also preserve dependencies and numerical requirements. Floating-point addition can change its rounded result when reordered, unlike our small exact integer example. Cornell’s cache-blocking exercise develops this idea with real loop nests.
Fewer bytes moved is evidence, not a stopwatch reading
Latency is how long an individual request takes. Bandwidth is the amount of data transferred per unit time. Locality can reduce how much traffic a workload creates, but fewer cache misses do not automatically translate into the same proportional reduction in application runtime. Computation, prefetching, concurrent requests and other bottlenecks affect the result.
The lab reports fetched bytes and teaching ticks separately. It makes no bandwidth claim about your device. Sequential access may benefit from hardware prefetching, which anticipates future lines; our cold, demand-filled cache does not prefetch. Measure the actual program on representative inputs before turning this model’s outcome into a production speedup claim.
A row-first traversal is favorable only when rows are laid out contiguously for that representation. Column-major storage changes the relationship. Object indirection, element size and padding also change which useful values share a line. Start with the actual layout and address trace, rather than treating a loop’s visual nesting as sufficient evidence.
Predict the line sequence, then test it
Check your reasoning
- With four-byte lines and one cache slot, what happens for 0, 3, 4, 0?
- Miss, hit, miss, miss. Addresses 0 and 3 share line 0. Address 4 replaces it with line 1, so the final read refills line 0. Total: 3 misses, 1 hit, 12 fetched bytes and 31 teaching ticks.
- Does a cache eviction free the program’s heap allocation?
- No. This eviction discards a cached copy. Allocation lifetime and cache residency are separate concerns.
- With eight-byte lines and two slots, how many misses does the sixteen-byte column preset cause?
- Two. Its entire two-line working set fits after the first fill of each line. The other fourteen reads hit.
- Can two address traces with checksum 136 be assumed equivalent?
- No. Different addresses or read counts can produce the same sum. Inspect the complete workload and the operation’s semantics.
Your turn: repair four cache access plans
The lab starts with a correct sum that exceeds a cache-miss budget. Run program, then Show final state to see the red target message. This is a performance-target failure, not an invalid memory read. Each experiment states which settings you may change. Keep the required addresses and how many times each is read; a matching checksum alone cannot prove that you kept the work.
Open Instructions to edit. Hints explain the next step, and a second disclosure gives one repair with its expected evidence. Green means the stated tutorial target was met on the current run. Editing makes that evidence stale until you run again. These are guided learning checks; harder unguided problems belong in the practice bank.
- Change the loop order: sum every cell once with at most four misses, keeping two cache slots.
- Keep all four rows cached: preserve column order and find the smallest capacity that meets the four-miss target.
- Use a selected cell twice: keep the six required reads and group reuse to reduce six misses to three.
- Finish both passes on a small region: keep all 32 reads while reducing eight fills to four.
A cache fetches a whole line of nearby bytes. Reading those bytes before their line is evicted reuses that transfer. Compare the same 16 addresses in sequential and column order to see how access order changes cache misses and fetched bytes.
Open The cache locality workbench. Editable controls require JavaScript; the worked examples above and below remain readable.
Published by GOAT Engineer. The lab uses a temporary browser session; reloading clears its design and evidence. Privacy policy · [Contact the team](mailto:[email protected]).
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.