Memory Access Patterns and CPU Cache Performance
System DesignModel answerLast updated
Analyze how traversal order affects performance in large arrays, explain the cache hierarchy and address translation, and identify practical optimizations.
You're asked to demonstrate understanding of how modern CPUs interact with memory by answering three related questions. Provide answers that show you grasp the underlying hardware mechanics, not just textbook definitions.
Part 1: Array Traversal Performance
You have a large 2D array of 8-byte floating-point values laid out in row-major order (C-style). Compare two ways of iterating through it:
- Sequential traversal: outer loop iterates rows, inner loop iterates columns
- Strided traversal: outer loop iterates columns, inner loop iterates rows
Which approach performs better and why? Under what conditions does the performance gap widen significantly? If your algorithm requires column-wise processing, what techniques would you use to improve performance?
Part 2: Cache Hierarchy
Describe the L1 and L2 caches and contrast them with main memory. Your explanation should cover:
- Physical location and typical capacity
- Access latency (orders of magnitude)
- Whether they're private or shared between CPU cores
- What occurs when requested data isn't found in cache
Part 3: Translation Lookaside Buffer
Explain the purpose of the TLB and what happens during a TLB miss. How might TLB behavior impact the strided traversal scenario from Part 1? What strategies can mitigate TLB-related performance issues?
Hints
Hint 1
Think about what data gets loaded when you access a single array element - CPUs don't fetch one byte at a time
Hint 2
Consider both the distance between consecutive accesses and the total amount of data being touched
Hint 3
Address translation involves walking data structures in memory; the TLB exists to avoid doing this repeatedly
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Array Traversal Performance
Sequential traversal significantly outperforms strided traversal in row-major layouts.
Why sequential wins:
Memory moves in cache lines, typically 64 bytes. When you access array[0][0], the CPU loads an entire cache line containing 8 consecutive doubles (64 bytes ÷ 8 bytes each). Sequential traversal visits all 8 elements before needing the next cache line—7 out of 8 accesses hit cached data.
Strided traversal jumps by the full row width between accesses. For a 1000-column array, accessing array[0][0] then array[1][0] means jumping 8000 bytes. Each access likely needs a new cache line from memory, wasting 87.5% of each loaded line.
When the gap widens:
- Small arrays (under 1 MB): 2-3× slowdown, most data stays in L2/L3
- Large arrays (hundreds of MB): 10-100× slowdown due to:
- Every access misses cache, forcing slow DRAM reads
- Evicting recently-used data (thrashing)
- Hardware prefetchers struggle with irregular patterns
- TLB pressure from touching many pages
Optimization techniques:
- Reorder loops if the algorithm permits:
// Change from column-first to row-first
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
process(array[i][j]);
- Cache blocking (tiling): Process small rectangular blocks that fit in cache:
const int TILE = 64;
for (int ii = 0; ii < rows; ii += TILE)
for (int jj = 0; jj < cols; jj += TILE)
for (int i = ii; i < min(ii+TILE, rows); i++)
for (int j = jj; j < min(jj+TILE, cols); j++)
process(array[i][j]);
-
Transpose once: If you need repeated column access, pay the one-time transpose cost upfront, then operate on rows
-
Layout redesign: Switch to column-major storage, or use hybrid layouts like blocked formats
Part 2: Cache Hierarchy
The hierarchy from fastest to largest:
L1 cache:
- 32-64 KB per core
- ~4 clock cycles (~1 nanosecond at 3 GHz)
- Private to each core, often split into instruction (L1i) and data (L1d)
- Holds the actively executing code's hot data
L2 cache:
- 256 KB - 1 MB per core
- ~12 cycles (~3-5 ns)
- Typically private per core
- Catches L1 spillover
L3 cache (not mentioned but relevant):
- 8-32 MB shared across all cores
- ~40 cycles (~10-20 ns)
- Reduces traffic to main memory for multi-threaded workloads
Main memory (DRAM):
- Gigabytes to terabytes
- ~200-300 cycles (~50-100 ns)
- Off-chip, accessed via memory controller
- Shared system-wide
Key contrasts:
- Technology: L1/L2 use fast on-die SRAM; main memory uses denser, slower DRAM on separate chips
- Speed: Each level is 3-10× slower than the previous; L1 is ~100× faster than DRAM
- Capacity: Each level is 10-100× larger than the faster level above it
Cache miss behavior:
On an L1 miss, the CPU checks L2, then L3, then DRAM—each miss adds the next level's latency. A complete miss to DRAM costs ~100 ns, enough time for a modern CPU to execute 300 instructions if it had the data.
Data moves in 64-byte cache lines, exploiting spatial locality—accessing one byte brings 63 neighbors along.
Private vs shared impact:
Private caches (L1/L2) mean each core maintains its own copy. When one core writes to shared data, cache coherence protocols must invalidate or update copies in other cores' caches, adding overhead in multithreaded programs. Shared L3 helps by providing a common cache that all cores can access without going to DRAM.
Part 3: Translation Lookaside Buffer
Purpose:
Programs use virtual addresses; hardware needs physical addresses to access memory. The TLB is a small cache storing recent virtual-to-physical address translations, avoiding the expensive page table walk on every memory access.
How translation works:
Without the TLB, translating a virtual address on x86-64 requires walking a 4-level page table—up to four dependent memory reads, costing 100-200 cycles. The TLB reduces this to a single-cycle lookup for cached translations.
Typical TLB capacity:
- L1 TLB: ~64 entries for 4 KB pages → 256 KB of address space
- L2 TLB: ~1500 entries → 6 MB of address space
TLB miss cost:
The CPU's page walk hardware must traverse page tables in memory—roughly 100-200 cycles. Frequent misses severely degrade performance.
Impact on strided traversal:
A 10,000×10,000 double array occupies 800 MB across 200,000 pages (at 4 KB per page). Strided access with 80 KB jumps touches a new page almost every access. The TLB holds only ~1500 translations, so you miss repeatedly, adding 150+ cycles to each element access beyond the cache miss penalty.
Mitigation strategies:
-
Huge pages: Using 2 MB pages reduces the 800 MB array to just 400 pages—easily cached in the TLB. Enable via OS configuration or
madvise(MADV_HUGEPAGE). -
Blocking: Keep your working set small enough that all touched pages' translations fit in the TLB (under ~6 MB of distinct pages).
-
Sequential access: CPUs can prefetch page table entries for predictable sequential patterns but struggle with irregular strides.
-
Reduce active data: Algorithm changes that touch less total memory keep TLB pressure low.
Measuring the impact:
Hardware counters reveal cache and TLB behavior:
perf stat -e cycles,instructions,cache-misses,dTLB-load-misses ./program
High ratios of misses to instructions confirm memory subsystem bottlenecks rather than compute limits.
Unified View
Modern performance depends on matching access patterns to hardware optimization: CPUs excel at sequential, localized accesses that exploit cache line prefetching and keep translations cached. Jumping by large strides breaks both caching and translation efficiency, paying full memory latency plus page walk overhead per access. Optimization means restructuring algorithms and data layouts to work with the hardware, not against it.