Sub topic 1
Why Memory Is Slower Than the CPU: The Memory Hierarchy
Prerequisites.
Assume you know arrays, pointers, structs, loops, and Big-O notation. You should also understand that a variable usually refers to data stored in memory, not inside the CPU itself.
The memory hierarchy
A CPU can execute instructions in less than a nanosecond, but main memory usually takes much longer. To reduce this gap, computers use several storage levels:
| Level | Typical location | Relative speed | Capacity |
|---|---|---|---|
| Registers | CPU core | Fastest | Tiny |
| L1/L2/L3 cache | CPU or nearby | Fast | Small |
| Main memory (RAM) | Memory modules | Slower | Large |
| Storage | SSD or disk | Slowest | Very large |
Caches store recently used memory. A cache hit means the CPU finds the required data there. A cache miss means it must fetch data from a slower level.
Cache lines: how data actually moves
A cache does not usually fetch one integer or one byte. It transfers a fixed-size block called a cache line, commonly 64 bytes. If the CPU reads one element, nearby elements may arrive with it.
This makes data layout important. A sequential scan can use most of each fetched line. A scattered access pattern may fetch a line and use only one value.
Spatial and temporal locality
Spatial locality means that nearby addresses are likely to be used soon. Sequential array access has strong spatial locality.
Temporal locality means that recently used data is likely to be used again. Reusing a value or repeatedly processing a small buffer has strong temporal locality.
Traversal order: row-major access and strides
In C, a two-dimensional array uses row-major order. Elements in the same row are adjacent:
#include <stddef.h>
#define N 4096
double sum_rows(const double m[N][N]) {
double sum = 0.0;
for (size_t i = 0; i < N; ++i)
for (size_t j = 0; j < N; ++j)
sum += m[i][j];
return sum;
}The inner loop advances by sizeof(double), so it reads sequentially. Reversing the loops makes the inner loop jump by N * sizeof(double) bytes. This stride reduces spatial locality and can cause many cache misses, even though both versions are O(N²).
Exercise
Why can two O(N²) loops over the same matrix have different running times?
Show answer
Their access strides can differ. Sequential access uses cache lines efficiently, while large-stride access may fetch a new line for nearly every element.