Domain tracks · L2Mechanical sympathy: CPU caches and memory

Mechanical sympathy: CPU caches and memory

The same loop can run ten times faster or slower depending on how its data sits in memory. Learn how CPU caches work, so you can lay out data the way the hardware likes it.

L2 SeniorDomain tracks19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 8 Nov 2026 · How we check content
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

This is a made-up example. A team runs a Java service that counts events. One thread did all the counting. It was too slow, so they split the work across 4 threads.

To avoid locks, each thread got its own counter. They used an AtomicLongArray of size 4. Thread 0 adds to slot 0, thread 1 to slot 1, and so on, once per event. The main thread sums the slots at the end.

No thread touched another thread's counter. But with 4 threads, the job ran slower than with 1.

The cause was not in the code. It was in the hardware. The four counters took 32 bytes, side by side. A CPU cache moves memory in blocks of 64 bytes on most machines. 1 So the four counters shared one block, or at most two. Each write by one core took the block away from the other cores.

The fix was to space the counters 128 bytes apart. The code did the same work, and now it scaled with the number of threads. Martin Thompson shows the same effect in a short Java benchmark. 6

Section 2 of 8

The idea in simple words

Mechanical sympathy means writing code that suits how the machine really works. Martin Thompson took the term from the racing driver Jackie Stewart. 5 Stewart's point was that a great driver knows how the car works, not only how to steer it.

For you, the "car" is the CPU and its memory. A modern CPU is very fast. Main memory is slow next to it. To hide that gap, the CPU keeps small, fast caches close to each core.

The hardware decides what goes in the caches. But your data layout and access order decide whether they help or hurt.

The key idea. Memory is not one flat, equal-speed array. Data that is close together and read in order is fast. Data that is scattered, or written by many cores at once, is slow. The same algorithm can run ten times faster or slower because of this.

Section 3 of 8

How it works

The memory hierarchy

A CPU has several levels of cache. L1 is the smallest and fastest. L2 is bigger and slower. Many CPUs also add a third level, L3. 1 Behind them all is main memory (DRAM).

The table below is old. It shows Intel's figures for the Pentium M, a laptop CPU from the early 2000s, as given in Drepper's 2007 paper. 1 Newer CPUs differ, so read them as orders of magnitude only.

Where the data isAbout how long
Register1 cycle or less
L1 data cache3 cycles
L2 cache14 cycles
Main memory240 cycles

This chip had no L3. Most CPUs today have an L3 between L2 and main memory. 1

So a read from main memory can cost as much as about 80 reads from L1. The latency numbers lesson puts a main memory read at about 100 ns.

Cache lines

The cache does not load single bytes. It loads a whole cache line. Early caches used 32-byte lines. The norm is now 64 bytes. 1 Some CPUs use 128 bytes, such as Apple's M1. 10 When you read one 8-byte long, you also get the 56 bytes around it.

This rewards spatial locality: data you use together should sit together. It also rewards temporal locality: data you used a moment ago is probably still in the cache.

Prefetching: why sequential beats random

When you read memory in order, the CPU notices. It loads the next cache line before you ask for it. This is hardware prefetching. 1 Walking an array has a fixed stride, so the CPU can predict it. 4

Drepper measured this on a Pentium 4. He walked a large list of small elements, bigger than every cache. In memory order, each element cost about 9 cycles, thanks to prefetching and because 8 elements fit in one line. In random order, it cost 450 cycles and more. 1 That is about 50 times slower, for the same work.

Arrays versus linked structures

A linked list, tree or hash map with chained nodes puts each node somewhere in memory. To find the next node, the CPU must first load the current one. This is pointer chasing. The CPU cannot fetch ahead, because it does not know the next address yet.

The Disruptor paper says this can make memory access "more than 2 orders of magnitude less efficient". 4 That is one reason the LMAX team built the Disruptor on a pre-allocated ring buffer, not a linked list. 4

Array of structs versus struct of arrays

A worked example: say each Order object has 10 fields, about 80 bytes. A report sums only price. With an array of Order objects, each 64-byte line brings in at most one price. The other 56 bytes are wasted. In Java, an array of objects holds references, so each item also costs a pointer hop.

Now store each field in its own array: double[] prices, long[] ids, and so on. One line now holds 8 prices. The loop touches about 8 times fewer lines. This is a struct of arrays.

Drepper gives a related example. A loop needs only two fields of an order struct, but the other fields are loaded too. He says the program could run "up to 5 times worse than it could". His advice is to split the struct. 3

The order of the loop matters as much as the layout. In Drepper's matrix multiplication, changing the order of memory reads alone cut the run time to 23.4% of the original. With blocking and vector instructions too, it reached about 10%. 3 That is a ten-times gain with the same maths.

False sharing and padding

Step through the bug from the story.

Two threads write their own counters, but the counters share one cache line Core 1thread T1 adds to A Core 2thread T2 adds to B A | B | …A | B | …one 64-byte line holds A and B A+1 | B | …invalidT1 writes A · core 2 loses the line invalidA+1 | B+1 | …the line moves on every write A | paddingB | paddingA and B now on different lines✓ each core keeps its own line SeniorPath
  1. Thread T1 adds to counter A. Thread T2 adds to counter B. They never touch each other's counter. But A and B sit next to each other, so they are in the same 64-byte cache line. Each core has a copy of that line.
  2. T1 writes A. Before a core writes a line, it must own it. So the other core's copy of the whole line is marked invalid. Core 2 did nothing wrong, but it lost B too.
  3. Now T2 writes B. Core 2 must get the line back, and core 1's copy becomes invalid. This repeats on every write. The cores spend their time moving one line back and forth. This is false sharing.
  4. The fix is padding: put at least one cache line of unused bytes after A, so B starts on a new line. The JDK pads by 128 bytes. Now each core owns its own line and keeps it. No line moves between the cores.
Step 1 of 4

Each core can keep its own copy of a cache line in its cache. Before a core writes to a line, the other cores' copies are marked invalid. 1 So if two threads write two different variables in one line, the line moves between the cores on every write. This is false sharing. 4

The fix is padding: unused bytes that push hot variables onto separate lines. 6 The JDK pads by 128 bytes by default, not 64. 8 In the story, the fix looks like this:

// 16 longs = 128 bytes between slots; the first block stays empty
AtomicLongArray counts = new AtomicLongArray((threads + 2) * 16);
// thread i: counts.incrementAndGet((i + 1) * 16)

A Java array is not aligned to a cache line. Slot 0 sits next to the array header, so the code leaves the first block empty.

The JDK uses an internal annotation for this, @Contended. Its docs warn that it "will nearly always add significant space overhead to objects". 7 By default, the JVM obeys it only in trusted JDK classes. Your own code needs the flag -XX:-RestrictContended. 8

In everyday Java, use LongAdder for a shared counter. It keeps a table of counter cells, each padded with @Contended. 9

Branch prediction and NUMA, briefly

CPUs "invest heavily in branch prediction". They guess which way an if will go and start work early. A wrong guess wastes that work. 3 If a branch goes one way or the other at random, the CPU often guesses wrong, and a hot loop slows down.

Large servers have several CPU sockets, each with its own memory. This is NUMA. Reading memory attached to another socket costs more. 2 In Drepper's test, reading memory one hop away was about 20% slower. 2 Bigger machines have more hops, so the cost can be higher. 2

Measure, do not guess

Count the events with perf stat. Brendan Gregg shows commands such as: 11

perf stat -e cycles,instructions,cache-references,cache-misses ./app

With cycles and instructions, perf also prints instructions per cycle (IPC). Low IPC with many cache misses usually means the CPU is waiting for memory. 11 Many hardware counters may not be available inside a virtual machine. 11

Compare layouts with a real benchmark harness: JMH for Java 13, or Criterion.rs for Rust. 12 JMH's own README says a good harness does not free you from benchmarking pitfalls. 13

Section 4 of 8

Trade-offs

ChoiceGood forCostWatch out for
Array, read in orderFast scans. The CPU prefetches.Inserting in the middle is slow.Fixed size or costly resizing.
Linked list or treeCheap inserts and deletes.Pointer chasing. Each step may wait for memory.Fine for small or cold data.
Struct of arraysLoops that read a few fields of many items.Code is harder to read. One item is spread across arrays.Only worth it on hot loops you measured.
Padding hot fieldsStops false sharing between threads.More memory per object. 7Pad only fields that different threads write often.
Ignore layoutSimple, readable code.Can be many times slower on hot paths.Fine for most code. Measure first.
Section 5 of 8

At work: how a senior uses this

  • Ask "is this on the hot path?" first. Most code is not. Do not trade clarity for cache tricks there.
  • Run perf stat on the real workload before you change layout. Check cache misses and IPC.
  • When adding threads makes a job slower, suspect false sharing. Look for counters, flags or indexes that different threads write, sitting side by side.
  • In Java, try LongAdder for hot shared counters before you pad an array by hand.
  • Prefer arrays for big collections you scan often.
  • For big scans, ask which fields the loop really reads. Move cold fields to a separate object.
  • Prove each change with a benchmark on hardware like production.
Section 6 of 8

With AI

What to ask the agent

"Here is our hot loop and the class it reads. List each field the loop uses. Suggest a layout that puts those fields in fewer cache lines, and explain the trade-off."

"Write a JMH benchmark that compares an array of objects with a struct of arrays for summing one field over 10 million items. Include warm-up and use a Blackhole."

What to check yourself

  • Every speed claim the agent makes is backed by a benchmark you ran, not by reasoning alone.
  • The benchmark uses JMH or criterion, with warm-up and several runs. A loop timed with System.nanoTime() is not enough.
  • Any padding uses at least 128 bytes between hot fields, like the JDK default, and is limited to fields that really cause contention.
Section 7 of 8

Check yourself

1. Two threads each add to their own counter, A and B. The counters are next to each other in memory. Adding a second thread made the program slower. What is the most likely cause?

Show answer

False sharing. A and B are in the same cache line, so the cores keep taking the line from each other. Each thread writes only its own counter, so no data is lost. But a core must own the whole cache line to write to it, so the line moves between the cores on every write.

2. You walk 10 million items. Which layout is usually fastest?

Show answer

An array, read from start to end. An array read in order has a fixed stride. The CPU detects it and prefetches the next cache lines. In a linked list, the CPU must load each node to find the next one.

3. About how much slower is a read from main memory than a read from the L1 cache?

Show answer

About 10 to 100 times. Drepper's table for a Pentium M gives about 3 cycles for L1 and about 240 cycles for main memory, roughly 80 times. Exact numbers vary by CPU.

4. Your benchmark says a new data layout is 3 times faster. What should you check before you trust it?

Show answer

Whether it ran in a proper harness such as JMH, with warm-up and several runs, and whether perf stat shows fewer cache misses. Micro-benchmarks are easy to get wrong. JMH asks you to study its samples of common mistakes. Hardware counters show whether the cause is really fewer cache misses.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 13 sources and related lessons
  1. Ulrich Drepper, “What every programmer should know about memory, Part 2: CPU caches”, LWN.net, 2007 (opens in a new tab)
    Cache levels, access times in cycles, 64-byte cache lines, prefetching, and measured sequential versus random list walks (section 3).
  2. Ulrich Drepper, “What every programmer should know about memory, Part 4: NUMA support”, LWN.net, 2007 (opens in a new tab)
    What NUMA is, the NUMA factor, and measured costs of reading memory on another node (section 5).
  3. Ulrich Drepper, “What every programmer should know about memory, Part 5: What programmers can do”, LWN.net, 2007 (opens in a new tab)
    Struct layout, hot and cold data, the matrix multiplication speed-ups, and branch prediction hints (section 6).
  4. Martin Thompson, Dave Farley, Michael Barker, Patricia Gee and Andrew Stewart, “Disruptor: High performance alternative to bounded queues for exchanging data between concurrent threads”, LMAX, 2011 (opens in a new tab)
    Why linked queues are slow on modern CPUs, cache lines, false sharing, and prefetching on arrays.
  5. Martin Thompson, “Why Mechanical Sympathy?”, Mechanical Sympathy blog, 15 July 2011 (opens in a new tab)
    Where the term comes from (the racing driver Jackie Stewart) and why it matters for software.
  6. Martin Thompson, “False Sharing”, Mechanical Sympathy blog, 30 July 2011 (opens in a new tab)
    A short Java benchmark with and without padding, and why cores pass a cache line back and forth.
  7. OpenJDK source, jdk.internal.vm.annotation.Contended (Javadoc) (opens in a new tab)
    The JDK's annotation for fields that suffer false sharing, and its warning about extra memory.
  8. OpenJDK source, HotSpot runtime/globals.hpp (JVM flags) (opens in a new tab)
    The flags ContendedPaddingWidth (128 bytes by default) and RestrictContended (@Contended only for trusted classes by default).
  9. OpenJDK source, java.util.concurrent.atomic.Striped64 (the base of LongAdder) (opens in a new tab)
    How LongAdder keeps a table of counter cells, each padded with @Contended to avoid false sharing.
  10. Go project, golang.org/x/sys commit “cpu: fix cpu cacheLineSize for arm64 darwin(a.k.a. M1)”, 2022 (opens in a new tab)
    Go pads for 128-byte lines on arm64 because Apple M1 reports 128-byte cache lines.
  11. Brendan Gregg, “Linux perf Examples” (opens in a new tab)
    perf stat commands for cache misses, how to read instructions per cycle, and the warning that VMs may hide hardware counters.
  12. Criterion.rs, README (opens in a new tab)
    Statistics-driven microbenchmarking in Rust that detects performance improvements and regressions.
  13. OpenJDK, JMH (Java Microbenchmark Harness), README (opens in a new tab)
    The standard Java benchmark harness, with samples of common benchmarking mistakes.

Case studies: LMAX: LMAX: 6 million orders a second on one thread · Riot Games: Making VALORANT servers 20 times faster for 128 tick

Related: Latency numbers and back-of-envelope maths · Locks, atomics and deadlocks · Tail latency and queueing · OS essentials for backend engineers

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper