Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. The memory hierarchy
    4. Cache lines
    5. Measuring it: row by row or column by column
    6. std::vector against std::list: chasing pointers
    7. Arrays of structs and structs of arrays
    8. Which one should I use?
    9. Under the hood
    10. Common pitfalls
    11. Timing work the compiler removed
    12. Struct-of-arrays vectors that fall out of step
    13. Try it yourself

    Module 9 · Performance

    9.2Caches and data-oriented design

    Why the same amount of work can run ten times faster when data is laid out well: the memory hierarchy, cache lines, locality, vector against list, arrays of structs against structs of arrays, and how to time code honestly.

    About 30 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. The memory hierarchy
    4. Cache lines
    5. Measuring it: row by row or column by column
    6. std::vector against std::list: chasing pointers
    7. Arrays of structs and structs of arrays
    8. Which one should I use?
    9. Under the hood
    10. Common pitfalls
    11. Timing work the compiler removed
    12. Struct-of-arrays vectors that fall out of step
    13. Try it yourself

    Key terms

    cache
    A small, fast memory inside the processor that keeps copies of recently used parts of main memory (RAM). There are usually three levels: L1, L2 and L3.
    cache line
    The block of memory a cache loads and keeps as one piece: 64 bytes on this platform. Reading one byte brings in its whole line.
    cache miss
    A read whose data isn't in the cache, so the processor waits for a slower level or for RAM. A hit is a read the cache can answer.
    spatial locality
    Using data that sits close to data you just used, so it's already in the same cache line or the next one.
    temporal locality
    Using the same data again soon, while it's still in the cache.
    prefetcher
    Hardware that watches which addresses a loop reads and loads the next cache lines before the loop asks for them.
    array of structs (AoS), struct of arrays (SoA)
    Two layouts for many records: a vector of whole structs, or one struct holding a separate vector for each field.
    data-oriented design
    Choosing how to store data by how the program reads it, so the hot loops read only the bytes they need, in order.

    Two loops can do exactly the same additions and differ ten times in speed. The difference is where their data is. The processor can add numbers far faster than main memory can deliver them, so most fast code is fast because it reads memory in an order the hardware is good at. This lesson shows what that order is, measures it, and shows how to lay out data so your loops get it.

    In 30 seconds

    • Reading RAM takes hundreds of times longer than an addition. Small caches inside the processor hide most of that, when they can.
    • Memory moves in 64-byte cache lines. Reading data in order uses every byte of each line; jumping around wastes most of them.
    • A std::vector read in order is the fastest thing to scan. Linked structures like std::list make each step wait for memory.
    • Store data the way your loops read it: if a loop needs one field of a million records, keep that field in its own array.

    The memory hierarchy

    A processor keeps its working values in registers, a few dozen named slots inside it. Everything else lives in RAM, which is big but far away. In between sit the caches: small, fast memories that keep copies of what was used recently. Each level is bigger and slower than the one before:

    LevelTypical sizeTime for one read (rough)
    Registersa few hundred bytesno wait
    L1 cache32–64 KB per coreabout 1 ns
    L2 cache0.5–2 MB per corea few ns
    L3 cachetens of MB, shared by all cores10–20 ns
    RAMmany GB80–100 ns

    These are orders of magnitude for desktop and server processors today, not exact numbers. The machine that checked this course’s examples has 48 KB of L1 data cache and 1.25 MB of L2 per fast core, and a 30 MB L3. In 100 ns, a core can do several hundred additions, so a program that keeps missing the cache spends most of its time waiting. “Under the hood” measures each level.

    Cache lines

    Memory doesn’t move one byte at a time. When you read one int, the processor loads the whole cache line around it, 64 bytes, into the cache. C++17 added a constant that holds the compiler’s idea of that size, std::hardware_destructive_interference_size in <new>:

    #include <new>
    #include <print>
    
    std::println("{}", std::hardware_destructive_interference_size);

    Output

    64

    Two habits follow from cache lines:

    • Spatial locality: after you read one element, its neighbors are already in the cache. A loop that reads an array in order uses all 16 ints of every line it loads.
    • Temporal locality: a line stays in the cache for a while, so reusing data soon after you first read it is cheap.

    The prefetcher helps too: when a loop reads lines in order, it loads the next ones before you ask, so a forward scan hardly ever waits.

    Measuring it: row by row or column by column

    To see any of this, you need to measure. std::chrono::steady_clock, from <chrono>, is a clock that only moves forward, which makes it the one to time with. now() reads it, and subtracting two readings gives a std::chrono::duration; std::chrono::duration<double, std::milli> holds it as a number of milliseconds. The helper best_ms below runs some work five times and keeps the fastest run.

    The program sums a grid stored flat in row-major order two ways. Row by row reads memory in order. Column by column jumps a whole row ahead, 16,000 bytes here, at every step, so each read lands in a different cache line and uses 4 of its 64 bytes:

    #include <algorithm>
    #include <chrono>
    #include <cstddef>
    #include <print>
    #include <vector>
    
    template <typename F>
    double best_ms(F work) {
        double best = 1e9;
        for (int run = 0; run < 5; ++run) {
            auto start = std::chrono::steady_clock::now();
            work();
            auto stop = std::chrono::steady_clock::now();
            std::chrono::duration<double, std::milli> took = stop - start;
            best = std::min(best, took.count());
        }
        return best;
    }
    
    int main() {
        const std::size_t rows = 4000;
        const std::size_t cols = 4000;
        std::vector<int> grid(rows * cols, 1);
        long by_rows = 0;
        long by_cols = 0;
        double row_ms = best_ms([&] {
            by_rows = 0;
            for (std::size_t r = 0; r < rows; ++r) {
                for (std::size_t c = 0; c < cols; ++c) {
                    by_rows += grid[r * cols + c];
                }
            }
        });
        double col_ms = best_ms([&] {
            by_cols = 0;
            for (std::size_t c = 0; c < cols; ++c) {
                for (std::size_t r = 0; r < rows; ++r) {
                    by_cols += grid[r * cols + c];
                }
            }
        });
        std::println("row by row:       {:6.1f} ms", row_ms);
        std::println("column by column: {:6.1f} ms", col_ms);
        std::println("same sum: {}", by_rows == by_cols);
    }

    Output from one run (it varies)

    row by row:          5.1 ms
    column by column:   26.2 ms
    same sum: true

    Same grid, same additions, same answer: column by column is about five times slower on this machine. Your numbers will differ; the pattern won’t. When an algorithm needs to go down columns, such as totaling each feature over many samples, you can usually still read row by row and keep one running total per column. The “Try it yourself” task does that, and Matrix multiplication uses the same trick.

    Three rules make a timing mean something:

    • Build with optimization and without sanitizers. These examples use -O2 and no sanitizers. -O0 and sanitizers slow different code by different amounts, so they can change which version wins, not only the numbers. Keep the sanitizers for every other run.
    • Repeat, and keep the best run. The first run also pays for the operating system handing over fresh memory, and other programs on the machine add noise.
    • Use the result. The program prints whether the sums match, so the compiler must compute them. Work whose result is never used can disappear entirely; “Common pitfalls” shows it happen.

    std::vector against std::list: chasing pointers

    A std::list<T>, from <list>, stores each element in its own heap block, a node, with pointers to the previous and next nodes. Moving to the next element means reading a pointer and then waiting for the memory it points to: pointer chasing. When the nodes are scattered, every step is a cache miss, and the prefetcher can’t guess where the next one is.

    Sorting a list relinks its nodes without moving them, so afterwards the list’s order no longer matches the order of the nodes in memory. Here both containers hold the same two million numbers and get sorted, then summed:

    #include <list>
    #include <numeric>
    #include <print>
    #include <random>
    #include <vector>
    
    int main() {
        std::mt19937 rng(1);
        std::vector<int> numbers(2'000'000);
        for (int& n : numbers) {
            n = static_cast<int>(rng() % 1000);
        }
        std::list<int> linked(numbers.begin(), numbers.end());
        std::ranges::sort(numbers);
        linked.sort();
        long v = 0;
        long l = 0;
        double v_ms =
            best_ms([&] { v = std::reduce(numbers.begin(), numbers.end(), 0L); });
        double l_ms =
            best_ms([&] { l = std::reduce(linked.begin(), linked.end(), 0L); });
        std::println("vector: {:6.1f} ms", v_ms);
        std::println("list:   {:6.1f} ms", l_ms);
        std::println("same sum: {}", v == l);
    }

    Output from one run (it varies)

    vector:    0.2 ms
    list:    211.1 ms
    same sum: true

    The list is roughly a thousand times slower here, for three reasons. Each node is 24 bytes with GCC’s library (two pointers and the int, padded), plus the heap’s own bookkeeping, so the list is more than six times bigger than the vector’s 4 bytes per number: the vector’s 8 MB fits in this machine’s L3 cache, and the list doesn’t. The list’s nodes are visited in an order that jumps all over that memory, so nearly every step waits for RAM. And the vector’s loop is simple enough for the compiler to add several numbers per instruction (SIMD covers that). The same applies to any structure built from pointers: trees like std::map, and a std::vector<std::unique_ptr<T>> whose objects were allocated at different times.

    PerformanceDefault to std::vector

    A list’s strength is inserting in the middle without moving anything. In practice, a vector that moves a few thousand elements on insert still beats a list that misses the cache on every step. Reach for a linked structure only after measuring.

    Arrays of structs and structs of arrays

    Layout, alignment and padding showed how a struct’s bytes sit in memory. That matters most when a loop reads only part of each struct. A std::vector<Read> is an array of structs: all of read 0, then all of read 1. A struct of arrays keeps each field in its own vector instead, like struct Reads { std::vector<float> mean_qualities; std::vector<std::string> names; … };, and read i is spread across the vectors at index i.

    This program averages the quality of two million reads both ways. A Read is exactly one cache line. The struct-of-arrays side needs only its quality vector, so that’s all the program builds:

    #include <cstdint>
    #include <print>
    #include <vector>
    
    struct Read {
        std::uint64_t id;
        float mean_quality;
        float gc_fraction;
        std::uint32_t length;
        std::uint32_t flags;
        char name[40];
    };
    static_assert(sizeof(Read) == 64);
    
    int main() {
        const std::size_t n = 2'000'000;
        std::vector<Read> reads(n);
        std::vector<float> mean_qualities(n);
        for (std::size_t i = 0; i < n; ++i) {
            reads[i].mean_quality = static_cast<float>(i % 40);
            mean_qualities[i] = static_cast<float>(i % 40);
        }
        double aos = 0;
        double soa = 0;
        double aos_ms = best_ms([&] {
            aos = 0;
            for (const Read& r : reads) {
                aos += r.mean_quality;
            }
        });
        double soa_ms = best_ms([&] {
            soa = 0;
            for (float q : mean_qualities) {
                soa += q;
            }
        });
        std::println("array of structs: {:5.2f} ms, mean {}", aos_ms, aos / n);
        std::println("struct of arrays: {:5.2f} ms, mean {}", soa_ms, soa / n);
    }

    Output from one run (it varies)

    array of structs:  6.56 ms, mean 19.5
    struct of arrays:  0.80 ms, mean 19.5

    The struct of arrays is about eight times faster here. With an array of structs, each 4-byte quality brings in a whole 64-byte line; with a struct of arrays, one line holds 16 qualities:

    One cache line, two layouts
    One cache line, two layouts: each row is one value; each cell's width is its size in bytes.
    Value0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263Size
    std::vector<Read>id8 bytesquality4 bytesgc4 byteslength4 bytesflags4 bytesname40 bytes64 bytes
    Reads::mean_qualities[0]4 bytes[1]4 bytes[2]4 bytes[3]4 bytes[4]4 bytes[5]4 bytes[6]4 bytes[7]4 bytes[8]4 bytes[9]4 bytes[10]4 bytes[11]4 bytes[12]4 bytes[13]4 bytes[14]4 bytes[15]4 bytes64 bytes

    In an array of structs, one 64-byte cache line holds a single Read: an 8-byte id, then mean_quality, gc_fraction, length and flags at 4 bytes each, then a 40-byte name. A loop over qualities uses 4 of the 64 bytes. In a struct of arrays, one 64-byte line of the mean_qualities vector holds 16 qualities, and the loop uses all of them.

    The loop reads 8 MB instead of 128 MB, and 8 MB also fits in this machine’s 30 MB L3 cache, so after the first run it rarely needs RAM at all. Smaller data that fits in a faster level is the whole point.

    This is data-oriented design: start from the loops that run most often and store data so they read only what they need, in order. You don’t have to go all the way. A common middle ground is to split a struct into the fields the hot loops use and the rest (names, comments), kept in a second vector at the same index.

    Which one should I use?

    WhatWhenWhyHow
    std::vector of structsThe default: most loops use most fields of each record.One allocation, read in order, simple code.std::vector<Read> reads;
    Struct of arraysHot loops read one or two fields of many records.Each loop reads only the bytes it uses, 16 floats per cache line.struct Reads { std::vector<float> mean_qualities; … };
    Hot and cold splitA few fields are used constantly and the rest rarely.Keeps the common case small without splitting every field.Two vectors of structs, indexed the same way.
    std::list, std::map, pointers to objectsYou need what they offer (stable addresses, sorted order) more than scanning speed.Every step follows a pointer and can miss the cache.Measure first; std::vector plus sorting or std::flat_map often wins.

    Rule of thumb: keep data that’s used together stored together, read it in the order it’s stored, and measure before and after any change.

    Under the hood

    When a core reads an address, it checks L1, then L2, then L3, then goes to RAM, and keeps a copy of the line in the caches on the way back. A full cache makes room by throwing out, roughly, the line that was used least recently. So the size of the data a loop keeps touching, its working set, decides which level answers. This program measures each level by following a chain of indexes in random order through arrays of growing size, so the prefetcher can’t help and every read waits for the one before:

    #include <algorithm>
    #include <chrono>
    #include <cstdint>
    #include <numeric>
    #include <print>
    #include <random>
    #include <vector>
    
    // next[i] is the index to visit after i: one random loop through every index.
    std::vector<std::uint32_t> random_cycle(std::uint32_t n) {
        std::vector<std::uint32_t> order(n);
        std::iota(order.begin(), order.end(), 0u);
        std::shuffle(order.begin() + 1, order.end(), std::mt19937(42));
        std::vector<std::uint32_t> next(n);
        for (std::uint32_t i = 0; i < n; ++i) {
            next[order[i]] = order[(i + 1) % n];
        }
        return next;
    }
    
    int main() {
        std::uint32_t at = 0;
        for (std::uint32_t kb : {16u, 512u, 4096u, 131072u}) {
            auto next = random_cycle(kb * 1024 / 4);
            const int steps = 2'000'000;
            auto start = std::chrono::steady_clock::now();
            for (int s = 0; s < steps; ++s) {
                at = next[at];
            }
            std::chrono::duration<double, std::nano> took =
                std::chrono::steady_clock::now() - start;
            std::println("{:>6} KB: {:5.1f} ns per read", kb, took.count() / steps);
        }
        std::println("(last index {})", at);
    }

    Output from one run (it varies)

        16 KB:   1.3 ns per read
       512 KB:   3.6 ns per read
      4096 KB:  13.6 ns per read
    131072 KB: 121.4 ns per read
    (last index 16161475)

    Each level shows up: about 1 ns per read while the 16 KB fit in L1, a few ns from L2, over 10 ns from L3, and over 100 ns once 128 MB has to come from RAM. Printing the last index uses the result, so the compiler keeps the loops. Summing the grid row by row took about 0.3 ns per int (5.1 ms for 16 million): read in order, the prefetcher and full cache lines hide almost all of this wait.

    Threads add one more effect. Each core has its own L1 and L2, and when two cores write to different variables that share one cache line, the line has to travel between them on every write, even though the threads never touch the same variable. This is false sharing. Mutexes and atomics measures it and fixes it with alignas(std::hardware_destructive_interference_size), which puts each variable on its own line.

    Common pitfalls

    Timing work the compiler removed

    If nothing uses a loop’s result, the optimizer is allowed to delete the loop. Here sum is never used after the loop, and the “measurement” times nothing:

    #include <chrono>
    #include <print>
    #include <vector>
    
    std::vector<int> data(32'000'000, 1);
    auto start = std::chrono::steady_clock::now();
    long sum = 0;
    for (int x : data) {
        sum += x;
    }
    std::chrono::duration<double, std::milli> took =
        std::chrono::steady_clock::now() - start;
    std::println("{:.3f} ms", took.count());

    Output from one run (it varies)

    0.000 ms

    Thirty-two million additions don’t take zero milliseconds: the compiler saw that sum is never used and removed the loop. Print the result, as the earlier examples do. When a time looks too good to be true, check that the work still happens.

    Struct-of-arrays vectors that fall out of step

    A struct of arrays has a rule the compiler can’t check: every vector has the same length, and index i means the same read in all of them. Filter one vector and forget the others, and the names and qualities no longer match: here r2 gets r3’s quality, and then the loop runs past the end of the shorter vector, which GCC’s library checks stop:

    #include <cstddef>
    #include <print>
    #include <string>
    #include <vector>
    
    struct Reads {
        std::vector<std::string> names;
        std::vector<float> mean_qualities;
    };
    
    int main() {
        Reads reads{{"r1", "r2", "r3"}, {31.5f, 12.0f, 28.0f}};
        std::erase_if(reads.mean_qualities, [](float q) { return q < 20.0f; });
        for (std::size_t i = 0; i < reads.names.size(); ++i) {
            std::println("{} {}", reads.names[i], reads.mean_qualities[i]);
        }
    }

    This fails when it runs

    /usr/include/c++/15/bits/stl_vector.h:1263: constexpr std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::reference std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::operator[](size_type) [with _Tp = float; _Alloc = std::allocator<float>; reference = float&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.

    Make the rule an invariant: turn Reads into a class with private vectors and member functions, such as add and remove_low_quality, that change every vector together.

    Common pitfallSmall inputs hide memory costs

    An array of a thousand ints fits in L1, so every layout looks equally fast. Time with data as big as the real program’s, or the cache will make a bad layout look fine.

    Try it yourself

    Try it yourself

    This program sums each column of a 3,000 × 3,000 grid, the way you’d total each feature over many samples. It walks down each column, jumping a whole row at every step. Change it to read the grid row by row, with the same results.

    #include <cstddef>
    #include <print>
    #include <vector>
    
    int main() {
        const std::size_t rows = 3000;
        const std::size_t cols = 3000;
        std::vector<int> grid(rows * cols);
        for (std::size_t i = 0; i < grid.size(); ++i) {
            grid[i] = static_cast<int>(i % 7);
        }
        std::vector<long> column_sums(cols, 0);
        for (std::size_t c = 0; c < cols; ++c) {
            for (std::size_t r = 0; r < rows; ++r) {
                column_sums[c] += grid[r * cols + c];
            }
        }
        std::println("{} {} {}", column_sums[0], column_sums[1], column_sums[2]);
    }

    Expected output

    8998 9002 8999
    Show a hint

    Swap the two for lines so the outer loop goes over rows and the inner loop over columns. The body stays the same: column_sums[c] += grid[r * cols + c].

    Show a solution
    #include <cstddef>
    #include <print>
    #include <vector>
    
    int main() {
        const std::size_t rows = 3000;
        const std::size_t cols = 3000;
        std::vector<int> grid(rows * cols);
        for (std::size_t i = 0; i < grid.size(); ++i) {
            grid[i] = static_cast<int>(i % 7);
        }
        std::vector<long> column_sums(cols, 0);
        for (std::size_t r = 0; r < rows; ++r) {
            for (std::size_t c = 0; c < cols; ++c) {
                column_sums[c] += grid[r * cols + c];
            }
        }
        std::println("{} {} {}", column_sums[0], column_sums[1], column_sums[2]);
    }

    With rows outside, the inner loop reads grid in the order it's stored, one row after another, and adds each value to its column's running total. column_sums has only 3,000 entries (12 KB), so it stays in L1 the whole time. Each sum gets the same values in the same order, so the results are identical, and memory is read in order, as in the row-by-row example above.