Skip to content
systemcoding.dev
Fundamentals

The Memory Hierarchy: Registers, Cache, RAM and Storage

Learn why computers use layers of memory from registers to storage, how a cache line works, and how to read your own machine's cache sizes with a C program.

6 min read
Summarize in AI
Flat illustration of a hardware register drawn as bit fields with one field highlighted, with the C, Arm and Rust logos.

A computer cannot have memory that is large, fast and cheap at once. Fast memory is small and expensive, large memory is slow, and the gap between the two is wide enough that a processor would spend most of its time waiting if it used only one kind. The answer in every general-purpose computer is a hierarchy: a few very fast stores close to the CPU, backed by progressively larger and slower ones, arranged so that most accesses hit the fast layers.

This post names the layers, explains why the arrangement works, and shows how to read the cache sizes of the machine in front of you from C. It stays at the level every systems programmer needs, and it avoids quoting latencies, because those differ by chip and nobody should trust a number they have not measured on their own hardware.

The layers from fastest to slowest

LayerTypical size orderManaged bySurvives power loss
RegistersA few hundred bytesCompiler and CPUNo
L1 cacheTens of kilobytes per coreHardwareNo
L2 cacheHundreds of kilobytes to a few megabytesHardwareNo
L3 cacheMegabytes, shared by coresHardwareNo
Main memory (RAM)GigabytesOperating systemNo
Storage (SSD, disk)Hundreds of gigabytes to terabytesOperating system and filesystemYes

Registers are part of the instruction set: the program names them explicitly. Caches are invisible to the program. No instruction says "load this into L2", and the hardware decides what to keep. RAM is addressed through virtual memory, so the operating system maps it. Storage is accessed through files and the page cache, which is RAM used to keep recently read disk blocks.

Each step down is larger and slower. The reason is physical, not a design choice: a bigger memory has longer wires and more levels of decoding, and the technologies that make memory dense (DRAM cells for RAM, flash for SSDs) are slower than the transistors that make registers and SRAM caches.

Why a hierarchy works: locality

A hierarchy would be useless if programs touched memory at random. They do not. Two patterns hold for almost all code:

  • Temporal locality: an address used now is likely to be used again soon. A loop counter or a hot struct is the classic case.

  • Spatial locality: an address near one used now is likely to be used soon. Walking an array is the classic case.

Caches exploit both. They keep recently used data, and they load memory in blocks called cache lines instead of single bytes. On most x86-64 and many Arm processors a line is 64 bytes, so reading one int brings its neighbors along for free.

Reading your machine's cache sizes

You do not have to guess the numbers. On Linux with glibc 2.40, sysconf accepts cache parameters as glibc extensions, documented in the sysconf(3) manual page: _SC_LEVEL1_DCACHE_SIZE, _SC_LEVEL1_DCACHE_LINESIZE, _SC_LEVEL2_CACHE_SIZE and _SC_LEVEL3_CACHE_SIZE. They return 0 or -1 when the information is unavailable.

caches.cc
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>

static void show(const char *name, int key) {
    long v = sysconf(key);
    if (v > 0)
        printf("%-18s %ld bytes\n", name, v);
    else
        printf("%-18s not reported\n", name);
}

int main(void) {
    show("L1 data cache", _SC_LEVEL1_DCACHE_SIZE);
    show("L1 line size", _SC_LEVEL1_DCACHE_LINESIZE);
    show("L2 cache", _SC_LEVEL2_CACHE_SIZE);
    show("L3 cache", _SC_LEVEL3_CACHE_SIZE);
    show("page size", _SC_PAGESIZE);
    return 0;
}
Shell
gcc -std=c17 -Wall -Wextra caches.c -o caches
./caches

The numbers are those of one machine, a laptop with a 32 KiB L1 data cache, 1 MiB of L2 and 12 MiB of shared L3. Yours will differ:

Text
L1 data cache      32768 bytes
L1 line size       64 bytes
L2 cache           1048576 bytes
L3 cache           12582912 bytes
page size          4096 bytes

The command lscpu prints the same data in a table, and the files under /sys/devices/system/cpu/cpu0/cache/ expose each level as text. The page size is not a cache size, but it belongs in the picture: it is the unit the operating system moves between RAM and storage.

A hit, a miss and the cost of a miss

When the CPU loads an address it asks L1 first. If the line is there, that is a hit and the data arrives fast. If not, it is a miss, and the request goes to L2, then L3, then RAM. When the line arrives it is stored in the cache, possibly evicting an older line to make room. A miss at every level is paid in full in time spent waiting for DRAM, while the core stalls or runs other independent instructions.

The practical consequence is that the order you access memory matters as much as how many operations you do. Compare two ways of summing a matrix stored in C's row-major order:

sum.cc
#include <stdio.h>

#define N 1024

static int m[N][N];

int sum_rows(void) {
    int s = 0;
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            s += m[i][j];       /* walks memory in address order */
    return s;
}

int sum_cols(void) {
    int s = 0;
    for (int j = 0; j < N; j++)
        for (int i = 0; i < N; i++)
            s += m[i][j];       /* jumps N * 4 bytes between reads */
    return s;
}

int main(void) {
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            m[i][j] = 1;
    printf("%d %d\n", sum_rows(), sum_cols());
    return 0;
}
Text
1048576 1048576

Both functions return the same value and execute the same number of additions. The difference is the access pattern. sum_rows reads consecutive addresses, so each 64-byte line serves sixteen int reads before the next miss. sum_cols steps 4096 bytes between reads in the inner loop, so it touches a new line on every read and, when the matrix is larger than the cache, evicts lines before it comes back for their neighbors. The mechanism is the reason the second loop is the slower one on typical hardware. Measure with a profiler such as perf stat on your own machine before relying on any specific ratio.

RAM and storage in the picture

RAM is the layer the operating system manages. A program sees virtual addresses, and the kernel maps them to physical pages, bringing a page in from storage when a program touches one that is not resident, which is a page fault. Storage is the layer that persists: a file read goes into the kernel's page cache in RAM, and a second read of the same file is served from there without touching the device.

The hierarchy repeats the same idea at every boundary. L1 is a cache for L2, the caches are a cache for RAM, and RAM is a cache for storage. Each pair has a block size (cache line, page, disk sector) and a policy for what to evict.

When the hierarchy stops being a free lunch

Caching assumes locality, and some workloads do not have it. Chasing pointers through a large linked list or hashing keys into a table bigger than the cache means most accesses miss, and the program runs at the speed of the slowest layer it touches. Multi-core machines add a second cost: when two cores write to different variables on the same cache line, the line bounces between their caches, a problem called false sharing. Embedded microcontrollers often have no cache at all, and real-time code relies on their fixed access times instead.

Also inHardware
Taggedcbeginner
Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.