← Runtimes
Runtimes

Registers, caches, and main memory

Lines, sets, replacement, and what a miss costs.

Explain a memory access before timing it.

Outcome

Map addresses to cache lines and sets, predict hits and misses for an access order under a stated cache model, and say what a timing can and cannot establish.

Terminology (10)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Register
A small storage location inside the processor that instructions use directly for operands and results.
Main memory
The larger memory backing the caches. A cache miss can require a read from another cache or from main memory.
Cache line
A fixed-size block of bytes held by a cache. This lesson’s model uses 64-byte lines; real line sizes depend on the processor.
Set
The group of cache slots a given line may occupy. This model assigns line n to set n mod the number of sets.
Way
One slot in a set. A set with two ways can hold two lines at once.
Direct-mapped
A cache with one way per set, so each line has exactly one place it can go.
Hit and miss
A hit finds the needed line in the cache; a miss has to fetch it from a slower level.
Least recently used (LRU)
A replacement policy that removes the line whose most recent use is oldest.
Spatial locality
The tendency to read data near data that was just read, which whole-line fetches reward.
Typed array
A TypeScript view such as Int32Array over contiguous bytes in an ArrayBuffer.

Why access order matters

Processor instructions use registers directly, while larger data structures live in memory. Caches keep copies of memory blocks closer to the processor. A cache line is one such block: accessing one element can make nearby elements available too. Reading nearby data is spatial locality; returning to recently used data is temporal locality.

A cache has limited room, so an access order also determines which blocks must compete for space. The same amount of source-level work can therefore create different memory traffic. A stated cache model lets us reason about that traffic; a timing measures the complete program under particular machine and run conditions.

01Layout

Where do neighbouring elements live?

A sales report needs totals by store and by product from the same table of unit counts. Both jobs read every count once. Before changing the table layout to speed up the product report, find out what each access order asks the memory hierarchy to keep nearby.

The report keeps one flat table of 32-bit counts, with each store’s products together. Start by checking that storage assumption. Each program makes one store’s row, sixteen counts with one per product, and finds how far product 3’s count is from product 0’s.

Registers hold operands that processor instructions use directly. A running total may stay in a register, while table reads load counts through caches backed by main memory. The compiler decides where source variables go; this probe does not reveal that decision. Caches keep copies of memory in fixed-size lines, so a read can bring nearby counts close to the processor too.

TypeScript exposes no addresses. A typed array’s subarray reports its byteOffset into the shared ArrayBuffer instead.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// One store's row of the sales table: sixteen 32-bit unit counts, one per
// product. An Int32Array stores them back to back in one ArrayBuffer.

const storeRow = new Int32Array(16);
const fromProduct3 = storeRow.subarray(3);

console.log(`bytes per count: ${storeRow.BYTES_PER_ELEMENT}`);
console.log(
  `product 3's count starts ${fromProduct3.byteOffset - storeRow.byteOffset} bytes after product 0's`
);
How many bytes after product 0’s count does product 3’s count start?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

Put each example in the shown file and run the command. The layout and totals examples print the same values on every machine; the timing example prints numbers that belong to your machine.

02Lines and sets

Which reads hit, and which miss?

The store report reads neighbouring counts, while the product report skips from store to store. To test whether those skips lose useful data, model one cache with three numbers. The line size says how many bytes move together: the line number of an address is the address divided by the line size, rounded down. Give the cache a fixed number of sets, with each line assigned to set number line mod sets. Each set has a fixed number of ways, the lines it can hold at once.

A read hits when the line it needs is stored in its set. Otherwise it misses, the line is fetched from the next level, and it is stored in that set. With one way per set, storing it replaces whatever line was there.

The programs below reduce the report to 16 stores and 16 products, stored store after store. Per-store totals read it in row order: indexes 0, 1, 2, …. Per-product totals read it in column order: 0, 16, 32, …. Multiply an index by four to get its modeled byte address, with the table starting at address 0. Start with an empty cache separately for each job and count only reads of the unit counts. Allocations, totals and instruction fetches are outside this model.

The cache model for this question
PartValueMeaning
Line size64 bytesSixteen 4-byte counts per line; store r’s row is line r
Sets4Line n is stored in set n mod 4
Ways1Each set holds one line at a time
main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A regional sales table: units sold per store (rows) and product (columns),
// 32-bit counts stored store after store in one buffer. The count for
// (store, product) is at index store * products + product.

const stores = 16;
const products = 16;
const units = new Int32Array(stores * products).map((_, index) => index); // sample counts

// Per-store totals: each store's row, left to right (row order).
const storeTotals: number[] = [];

for (let store = 0; store < stores; store++) {
  let total = 0;

  for (let product = 0; product < products; product++) {
    total += units[store * products + product];
  }

  storeTotals.push(total);
}

// Per-product totals across stores: down each product's column (column order).
const productTotals: number[] = [];

for (let product = 0; product < products; product++) {
  let total = 0;

  for (let store = 0; store < stores; store++) {
    total += units[store * products + product];
  }

  productTotals.push(total);
}

const sum = (totals: number[]) => totals.reduce((a, b) => a + b, 0);

console.log(`store totals, row order: ${sum(storeTotals)} units`);
console.log(`product totals, column order: ${sum(productTotals)} units`);
Under the model in the table (64-byte lines, 4 sets, one line per set), how many misses does each order cause over the 256 reads?

03Replacement

Which line leaves a full set?

Two ways do not rescue the full column scan, but they can retain a row when the report returns to it sooner. Probe that case with reads from stores 0, 4, 0 and 8. In the same four-set model their lines all use set 0. Call those lines P, Q and R, and give the set two ways.

A miss in a full set must now choose a line to replace. Use exact least recently used (LRU) replacement: remove the line whose most recent read is oldest. Every read counts as a use, including a hit. Real cache designs can use other policies or approximations; this trace tests the stated model.

Reads in one two-way set, starting empty
ReadLineSet holds afterwards
1PP
2QP, Q
3PP, Q
4R?
A set with two ways is empty. The program reads lines P, Q, P, then R, all in this set. Under least-recently-used replacement, which line does R replace?

04What a miss costs

What can a timing tell you?

The model predicts extra misses for the product report. Their cost depends on where each line is found: a miss in the first-level cache can hit in another cache, and only some reads need main memory. For one published design, Intel’s optimization manual gives roughly 4 to 6 cycles for the first-level data cache, 14 for the second level and 50 to 70 for the shared third level on Skylake server processors. Reaching main memory adds another access path, whose latency depends on the system. These are vendor cache-latency figures for that design, not measurements from this report.

Those figures cannot turn 256 modeled misses into the report’s runtime. Real processors can prefetch lines and overlap memory requests with other work. Run both report jobs on a larger table to see whether the predicted disadvantage appears in a timing. Each timed job allocates its totals and computes them; the programs time more than memory reads.

Run the timing program with node as before; the JIT compiles the hot loops while they run.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Times both report jobs on a national sales table: 4096 stores × 4096 products,
// one unit in each cell. The numbers vary between machines, runs and engines;
// compare the two lines of one run.

const stores = 4096;
const products = 4096;
const units = new Int32Array(stores * products).fill(1);

function storeTotals(): Float64Array {
  const totals = new Float64Array(stores);

  for (let store = 0; store < stores; store++) {
    let total = 0;

    for (let product = 0; product < products; product++) {
      total += units[store * products + product];
    }

    totals[store] = total;
  }

  return totals;
}

function productTotals(): Float64Array {
  const totals = new Float64Array(products);

  for (let product = 0; product < products; product++) {
    let total = 0;

    for (let store = 0; store < stores; store++) {
      total += units[store * products + product];
    }

    totals[product] = total;
  }

  return totals;
}

for (const [name, job] of [
  ["store totals, row order", storeTotals],
  ["product totals, column order", productTotals]
] as const) {
  const start = performance.now();
  const totals = job();
  const elapsed = performance.now() - start;

  console.log(
    `${name}: ${totals.reduce((a, b) => a + b, 0)} units, ${elapsed.toFixed(1)} ms`
  );
}
On your machine the per-product totals (column order) take about four times as long as the per-store totals (row order). What does that run establish?

05Practice

Finish the cache model

Build the report’s diagnostic cache model so it can replay short address traces before you time a storage change. It reads a cache shape and the byte addresses a report probe supplies, then explains each read and summarizes the result. The exercises use fresh traces and cache shapes: first locate the reads, then track what stays cached, then handle competing lines with LRU. Each level supplies the parts that already work. The tool predicts its model’s behavior; it measures no hardware.

The cache model

Map addresses to lines and sets, decide hits and misses, then replace the least recently used line.

  1. easy · R-CACHE-V4-1 Map addresses to lines
  2. medium · R-CACHE-V4-2 Decide hits and misses
  3. hard · R-CACHE-V4-3 Replace the least recently used line
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.