Performance: allocation, locality, and data layout
What you will learn on this page
Section titled “What you will learn on this page”- Why performance work starts with a measurement and a stated budget, and how to measure without fooling yourself.
- What a heap allocation costs, how to count allocations in a test, and the usual ways to remove them from a hot loop.
- Why contiguous memory is usually faster to walk than memory reached through pointers, and what cache locality means.
- How array of structs and struct of arrays lay out the same data, what each costs in code, and when the second one is worth it.
- How
std::pmrmemory resources let a caller decide where a container’s memory comes from, for example a scratch buffer that is thrown away every frame.
The problem: a budget measured in milliseconds
Section titled “The problem: a budget measured in milliseconds”A game draws sparks, smoke, and rain as particles: small objects with a position, a velocity, and a remaining life. Every frame, the game moves each particle, ages it, removes the ones whose life has run out, and adds new ones from emitters. Then the renderer draws the survivors.
At 60 frames a second, a frame has 1000 ÷ 60 ≈ 16.7 milliseconds for everything: input, physics, sound, and drawing. If particles are allowed, say, 1 millisecond of that, then a design that is fine for a thousand particles may not be fine for a hundred thousand. Unlike most pages on this site, the question here is not only “is the design clear?” but “does it fit the budget?”, and that question has an answer only a measurement can give.
This page shows how to get that answer. It does not give you one: timings depend on the processor, the compiler, the flags, the data size, and what else is running, and a number measured on one machine is not a fact about your program.
Requirements
Section titled “Requirements”| # | Requirement | Why it matters |
|---|---|---|
| R1 | Every frame, move and age every particle, then remove the dead, keeping the order of the rest | The core loop; order is kept so that results are repeatable |
| R2 | Particles are added and removed all the time | Allocation per particle would happen every frame |
| R3 | Other code reads particles: the renderer, and queries such as “which are inside this box?” | The layout must serve readers that use different fields |
| R4 | Once warmed up, a frame allocates no heap memory | Allocation is a cost and a source of jitter, and it is easy to test for |
| R5 | Changing the layout must not change the results | A faster layout that gives different answers is a bug |
| R6 | Layout decisions are backed by measurements on the target, not by intuition | The point of this page |
R4 and R5 can be tested on any machine: the tests below count allocations and compare layouts exactly. R6 cannot: it is a process, and the page describes the process.
Step 1: measure before you optimize
Section titled “Step 1: measure before you optimize”A design change made for speed has a cost that is certain (more code, more rules, harder reading) and a benefit that is a guess until it is measured. So the order is always the same:
Text description of the diagram
State a budget, such as 1 millisecond per frame for particles. Measure the real workload in an optimized build. If it is within budget, stop and keep the simplest code. If not, profile to find where the time goes, change one thing, and measure again with the same inputs on the same machine. If the change made it faster and the tests still pass, keep it and measure again; if not, revert it and go back to the profile.
Diagram source (Mermaid)
flowchart TD
B["State the budget, for example 1 ms per frame for particles"] --> M["Measure the real workload in an optimized build"]
M --> Q{"Over budget?"}
Q -- no --> D["Stop: keep the simplest code"]
Q -- yes --> P["Profile to find where the time goes"]
P --> C["Change one thing"]
C --> M2["Measure again, same inputs and machine"]
M2 --> K{"Faster, and still correct?"}
K -- yes --> M
K -- no --> R["Revert the change"]
R --> PHow to measure without fooling yourself:
- Measure an optimized build. A Debug build (no optimization,
sanitizers, debug checks in the standard library) measures the
checks, not the design. This site’s build presets are all Debug
builds, so for timing, configure a separate build directory with
-DCMAKE_BUILD_TYPE=Release. - Time the part you care about, many times. Build the input outside the timed region, repeat the run, and report the median, which a single slow run caused by something else on the machine does not move much.
- Use a steady clock.
std::chrono::steady_clockdoes not jump when the system time is corrected; see Cache policies and invalidation for why that matters. - Use the result. An optimizer may delete work whose result is never used. Print a checksum of the output, so that the work has an observable effect.
- Change one thing at a time, and keep the inputs, machine, and flags the same between runs.
- Profile before guessing. A sampling profiler (on Linux, for
example,
perf recordandperf report) shows where the time goes. Hardware counters (perf stat) can show cache misses and branch mispredictions. Both tell you where to look; neither replaces timing the change.
The example has a benchmark program that follows these rules. It is shown in Measuring it yourself, after the designs it compares.
Step 2: allocation costs, and how to count them
Section titled “Step 2: allocation costs, and how to count them”A heap allocation (new, std::make_unique, a std::vector
growing, a std::string longer than its small-string buffer) asks the
allocator for a block of memory. The cost is more than the call:
- The allocator must find a free block of the right size and keep bookkeeping for it. That work varies with the allocator and with how fragmented memory is, so the time per call is not constant; that variation is jitter, which matters when a frame has a deadline.
- With several threads, allocators share some state, so threads that allocate at the same time can slow each other down.
- Separate allocations end up at separate addresses. Walking from one to the next is pointer chasing, which defeats the memory locality described in Step 3.
- Every allocation needs a matching free, which costs again.
None of this means “never allocate”. An allocation when a level loads, or once per report, is irrelevant. An allocation per particle per frame is the kind that adds up. The first design tool is therefore not a clever allocator but a count: find out how many allocations a piece of code makes, and make that number part of a test.
Counting allocations
Section titled “Counting allocations”C++ lets a program replace the global operator new: define a
function with the standard signature, and every new, every
std::make_unique, and every standard container that uses the default
allocator calls it. One exception: in an optimized build the compiler
may remove a new and delete pair whose memory never leaves the
function (C++14 allows it), so a count from one build type can differ
from another; keep allocation tests in one fixed configuration. The example’s counting version counts each call,
and can also be told to fail one call, for tests of what a failed
allocation leaves behind:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Replaces the global operator new for the programs this file is linked// into: the plain form and the aligned form, which std::pmr uses. The// array and nothrow forms call these by default, so they are counted// too.//// `calls` and `countdown`, declared at the top of this file, are atomics// so that counting is safe from any thread. memory_order_relaxed is// enough because they are only counts: no other data is published// through them.namespace {// Called first by every operator new below. Counts the call, then, if a// test asked for a failure, decides whether this is the call that fails.// countdown is -1 for "never fail", 0 for "fail this call", and a larger// number for "let that many more calls succeed first".// The load and the store are separate steps, not one atomic update, so// fail_after is only reliable in a program with one thread, which is how// the tests use it.void count_or_fail() { calls.fetch_add(1, std::memory_order_relaxed); // a failed call is counted too const int left = countdown.load(std::memory_order_relaxed); if (left == 0) { countdown.store(-1, std::memory_order_relaxed); // fail only once throw std::bad_alloc(); // what a real out-of-memory new throws } if (left > 0) countdown.store(left - 1, std::memory_order_relaxed);}} // namespace
// The plain form, used by `new T`, std::make_unique, and containers with// the default allocator. It must return usable memory or throw; it may// never return null.void* operator new(std::size_t size) { count_or_fail(); // new of zero bytes must still return a unique pointer, but malloc(0) // may return null, so ask for one byte instead. if (void* memory = std::malloc(size == 0 ? 1 : size)) return memory; throw std::bad_alloc();}
// The aligned form, used for types that need more alignment than malloc// guarantees, and by std::pmr's default resource in GCC 11's library.void* operator new(std::size_t size, std::align_val_t alignment) { count_or_fail(); const auto align = static_cast<std::size_t>(alignment); // align_val_t is an enum // Rounding up below adds up to align - 1 to size; this check makes // sure that sum cannot overflow past the largest std::size_t. if (size > SIZE_MAX - align) throw std::bad_alloc(); // Round size up to the next multiple of align: for align 64 and size // 100, (100 + 63) / 64 * 64 is 2 * 64 = 128. Integer division drops // the remainder, which is what makes this round up. const std::size_t rounded = (size + align - 1) / align * align; // C11's aligned_alloc required this // rounded is 0 only for a zero-byte request; ask for one block then. if (void* memory = std::aligned_alloc(align, rounded == 0 ? align : rounded)) return memory; throw std::bad_alloc();}
// The matching deletes. Memory from malloc and from aligned_alloc are// both released with free, so all four forms do the same thing; the// size and alignment arguments are not needed and are ignored.void operator delete(void* memory) noexcept { std::free(memory); }void operator delete(void* memory, std::size_t) noexcept { std::free(memory); }void operator delete(void* memory, std::align_val_t) noexcept { std::free(memory); }void operator delete(void* memory, std::size_t, std::align_val_t) noexcept { std::free(memory); }VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// How many times the global operator new has been called so far.[[nodiscard]] std::size_t allocations() noexcept;
// Counts the allocations made from its construction onwards.// It remembers the global count when it is created; count() is how much// the global count has grown since. It counts allocations from every// thread, and it never resets anything, so several counters can be// alive at once, each measuring from its own start.class AllocationCounter {public: AllocationCounter() noexcept : start_(allocations()) {} [[nodiscard]] std::size_t count() const noexcept { return allocations() - start_; }
private: std::size_t start_; // the global count at construction};How this code works: How fail_after makes one allocation fail
countdown starts at -1, which means “never fail”. A test that calls
heap::fail_after(2) sets it to 2. Then each call to either
operator new runs count_or_fail first:
| Allocation | countdown before |
What count_or_fail does |
countdown after |
|---|---|---|---|
| 1st | 2 | counts it, lets it through | 1 |
| 2nd | 1 | counts it, lets it through | 0 |
| 3rd | 0 | counts it, throws std::bad_alloc |
-1 |
| 4th | -1 | counts it, lets it through | -1 |
So fail_after(n) lets n allocations succeed and makes the next one
fail, once. The failed call is still counted, because calls is
increased before the decision. The throw happens before malloc is
called, so a failed allocation takes no memory, just as a real one
would not.
AllocationCounter does not change any of this. It only reads calls
when it is created and again in count(), and subtracts.
- The replacement applies to the whole program, so it lives in its
own file and only the demo and the allocation tests link it. A
program can replace each form of the global
operator newonly once. - Replace every form you need to see. The first version replaced
only the plain form, and one test counted nothing when it should have
counted several allocations: GCC 11’s standard library allocates
through the default
std::pmrmemory resource with the aligned form ofoperator new, which the counter had not replaced. Replacing the aligned form too fixed the count. A counter that misses allocations gives a confident wrong answer, so test the counter as well. - ThreadSanitizer cannot be used with it here. With Clang, which
the tsan preset uses, the TSan runtime is linked statically and
defines
operator newitself, so the linker refuses a second definition. Both programs that link the counter run one thread, so the tsan preset skips them.
Removing allocations from a hot loop
Section titled “Removing allocations from a hot loop”The usual fixes, in the order to try them:
| Fix | What it removes | Cost |
|---|---|---|
reserve a vector when the size is known |
Repeated growth: allocate, copy or move, free | Must know or estimate the size |
| Keep a container and reuse its capacity instead of making a new one | Allocation on every use: removing elements keeps capacity | Memory stays reserved after a peak |
Store objects by value in a container, not one new per object |
One allocation per object, and the pointer chasing | Objects move when the vector grows; pointers to them dangle |
Pass and loop by const&, and move instead of copying |
Copies of strings and vectors | None, usually |
| Give scratch containers a memory resource such as an arena (Step 5) | Heap calls for short-lived memory | The arena must outlive every container that uses it |
| An object pool or a custom allocator | Whatever is left, once measured | More code and more lifetime rules |
The last row is last on purpose. Null Object and Object Pool shows a pool and the lifetime rules it brings; most programs never need one once the first four rows are done.
Step 3: contiguous memory and locality
Section titled “Step 3: contiguous memory and locality”A processor does not read memory one byte at a time. It reads a cache line, a small aligned block (64 bytes on most current x86-64 processors and many ARM ones), and keeps recently used lines in small, fast caches close to the core. Reading something already in a cache is much faster than reading main memory. The processor also notices when a program walks memory in order and fetches the next lines before they are asked for.
So a program is fast at memory when it has
cache locality: it
uses every byte of each line it fetches, and it reads lines in an order
the processor can predict. A std::vector walked from front to back is
the best case: elements are next to each other, and the order is
simple. A std::list, or a vector of pointers to separately allocated
objects, is the worst common case: each element can be anywhere, so
each step may wait for main memory, and the line it waited for may hold
only one useful element.
This is why Containers and complexity
basics recommends std::vector by
default even where Big-O favours another container: Big-O
counts operations and ignores how long each memory access takes.
Step 4: the same particles, three layouts
Section titled “Step 4: the same particles, three layouts”The particle itself is plain data. There is no rule tying its fields
together, so it is a struct with public members:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One particle: plain data with no rule tying its fields together, so a// struct. update reads and writes the first five fields; the last three// are for drawing, and update's movement loop never reads them.struct Particle { float x = 0, y = 0; // position, in metres float vx = 0, vy = 0; // velocity, in metres per second float life = 0; // seconds left; at or below zero it is dead float size = 0; // drawing only, from here down std::uint32_t colour = 0; // a colour, packed into one 32-bit number std::uint32_t emitter = 0; // which emitter made it
// "= default" makes == compare every field in order, so tests can // check that two layouts hold identical particles. friend bool operator==(const Particle&, const Particle&) = default;};// Checked when compiling, not when running: if a change to the fields, or// a compiler that added padding, made the struct anything but 32 bytes,// the build would stop here.static_assert(sizeof(Particle) == 32, "eight 4-byte fields, no padding");Particle has eight 4-byte fields, 32 bytes in all. The update loop
uses the first five, 20 bytes; the last three are cold data for the
renderer, which the movement loop never reads; removal copies them
only when it moves a survivor. That split, between hot data
the busy loop uses and cold data it does not, is what layout
decisions are about.
All three layouts below have the same operations, so the tests can check that they agree. Each one is a separate class, because they are three designs to compare, not three implementations to choose between at run time: nothing calls them through a shared interface.
Array of structs
Section titled “Array of structs”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Array of structs: one vector, each particle's fields side by side.// The default choice: one allocation, contiguous, and simple.class ArrayOfStructs {public: void reserve(std::size_t n) { particles_.reserve(n); } // one allocation for n void add(const Particle& p) { particles_.push_back(p); } // copies p into the vector void update(float dt);
[[nodiscard]] std::size_t size() const noexcept { return particles_.size(); } // Returns a copy, so the caller cannot change a particle in place. // [i] does not check the index, which is why i must be below size(). [[nodiscard]] Particle particle(std::size_t i) const { return particles_[i]; } // A read-only view of every particle, without copying any. A span is a // pointer and a length; it is valid only until the vector next changes. [[nodiscard]] std::span<const Particle> all() const noexcept { return particles_; }
private: std::vector<Particle> particles_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One frame: move and age every particle, then remove the dead. dt is the// frame's length in seconds.void ArrayOfStructs::update(float dt) { // Particle& (a reference, not a copy) so the changes are made to the // particles in the vector itself. for (Particle& p : particles_) { p.x += p.vx * dt; p.y += p.vy * dt; p.life -= dt; } // erase_if removes every element for which the lambda says true, and // keeps the others in their original order. Removing never frees the // vector's memory: its capacity stays the same. std::erase_if(particles_, [](const Particle& p) { return p.life <= 0; });}One std::vector<Particle>: one allocation, every particle next to the
next, and code that reads like the problem. std::erase_if (C++20)
removes the dead in one pass and keeps the order of the rest. This is
the default, and most code should stop here.
Its weakness is the cold data. The update loop walks 32 bytes per particle and uses 20, so of each 64-byte cache line it fetches, 24 bytes are carried along unused.
Struct of arrays
Section titled “Struct of arrays”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Struct of arrays: one vector per field. A loop that reads only// positions, velocities, and lives reads only those vectors.//// Invariant: every column has the same length, and index i in each one// belongs to the same particle. That rule is why this is a class with// private columns and not a struct of public vectors.class StructOfArrays {public: void reserve(std::size_t n); void add(const Particle& p); void update(float dt);
// Any column would do: the invariant says they all have this length. [[nodiscard]] std::size_t size() const noexcept { return x_.size(); } // Builds a Particle from entry i of every column. [[nodiscard]] Particle particle(std::size_t i) const;
private: // Calls f on every column. Adding a field means adding it here, in // add, and in particle. // F is any callable taking a column. The columns have two different // types, vector<float> and vector<std::uint32_t>, so the callers pass // generic lambdas, `[](auto& column) { ... }`, which work for both. // Writing the list once keeps every "do this to all columns" step from // forgetting one. template <typename F> void for_each_column(F f) { f(x_); f(y_); f(vx_); f(vy_); f(life_); f(size_); f(colour_); f(emitter_); }
std::vector<float> x_, y_, vx_, vy_, life_; // read by update std::vector<float> size_; // not read by update std::vector<std::uint32_t> colour_, emitter_;};Struct of arrays
turns the layout around: one vector per field, so the movement loop reads five vectors from front to back and never
touches the other three. Each cache line it fetches is full of values it uses, and a
loop over plain arrays of float is also the shape that compilers can
most easily turn into vector (SIMD) instructions at higher optimization
levels, though whether they do depends on the compiler and flags.
The cost is in the code, and it shows how to classify the type:
- It has an invariant, so it is a class with private members:
every column has the same length, and index
iin every column belongs to the same particle. Astructwith eight public vectors would let any caller break that rule with onepush_back. - One particle is spread over eight places.
particle(i)must gather it, and every operation that adds or removes must touch every column. The privatefor_each_columnhelper keeps that list of columns in one place, so most operations cannot forget one;addandparticlestill name each field, because each field comes from a different member ofParticle. - Adding must not fail half way.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Appends one particle: one value to the end of each of the eight// columns. The hard part is failure. If the fifth push_back threw, four// columns would be one longer than the rest, and the invariant would be// broken. So all the allocating is done first, and the push_backs only// run once none of them can throw.void StructOfArrays::add(const Particle& p) { // Make room in every column first. reserve can throw, but it changes // no lengths, so a failure here leaves the columns in step. const std::size_t needed = size() + 1; // capacity() is how many the column can hold before it must allocate. // Doubling it, as push_back typically does, keeps adding cheap on average: a // column grows only now and then, not on every add. std::max covers an // empty column, whose capacity is 0. for_each_column([needed](auto& column) { if (column.capacity() < needed) { column.reserve(std::max(needed, 2 * column.capacity())); } }); // Every column now has room, and copying a number cannot throw, so // none of these can fail part way. x_.push_back(p.x); y_.push_back(p.y); vx_.push_back(p.vx); vy_.push_back(p.vy); life_.push_back(p.life); size_.push_back(p.size); colour_.push_back(p.colour); emitter_.push_back(p.emitter);}How this code works: StructOfArrays::add when an allocation fails
Take the failure test further down: four particles in columns whose
capacity is exactly 4, so adding a fifth must grow every column. Say
the third allocation fails, as it does when the test calls
heap::fail_after(2).
neededis 5.for_each_columnvisits the columns in order.x_has capacity 4, less than 5, so it reservesmax(5, 2 * 4), which is 8. That works:x_now has room for 8, but still holds 4.y_does the same, and also works.vx_tries to reserve 8, and the allocation throwsstd::bad_alloc. A failedreserveleaves its vector exactly as it was. The exception leaves the lambda,for_each_column, andadd. None of thepush_backlines has run.- Afterwards, every column still holds 4 entries, so the invariant holds. Two columns have extra capacity, which changes no particle.
- The next
addfinds thatx_andy_already have room, skips them, and reserves the other six. Then all eightpush_backcalls run, none of them allocates, and the size becomes 5.
The rule behind it: do everything that can fail before the first change anyone can observe.
If add called push_back on each column in turn, the third call
could throw std::bad_alloc after the first two had succeeded, and the
columns would no longer be the same length. So add first makes room
in every column. reserve can throw, but it never changes a length,
so a failure there leaves the invariant intact. Once every column has
room, push_back of a number does not allocate and cannot throw. The
growth is doubled by hand (2 * capacity), because reserving only one
more element each time would make every add copy every column.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same frame as ArrayOfStructs::update, column by column. The// movement loop touches only x_, y_, vx_, vy_, and life_; the removal// must then keep all eight columns in step, so it is written by hand.void StructOfArrays::update(float dt) { const std::size_t n = size(); for (std::size_t i = 0; i < n; ++i) { // entry i of each column is particle i x_[i] += vx_[i] * dt; y_[i] += vy_[i] * dt; life_[i] -= dt; } // Removing the dead must move every column the same way. erase_if on // one column cannot do it: the test is on life, and the other columns // would not know which entries went. Like std::remove_if, start at the // first dead particle: the living before it are already in place. // // `kept` counts the survivors found so far, and is also the index where // the next survivor belongs. Invariant: entries 0 to kept - 1 of every // column hold the survivors seen so far, in their original order. std::size_t kept = 0; // Skip the living at the front: they are already where they belong. while (kept < n && life_[kept] > 0) ++kept; for (std::size_t i = kept; i < n; ++i) { if (life_[i] > 0) { // Copy survivor i down to slot `kept` in every column. kept is // always less than i here (at least one dead entry came before // i), so this only moves entries towards the front, over dead ones or // ones already copied. for_each_column([kept, i](auto& column) { column[kept] = column[i]; }); ++kept; } } // Cut every column to the survivors. Shrinking with resize keeps the // capacity, so a later add does not need to allocate. for_each_column([kept](auto& column) { column.resize(kept); });}How this code works: Removing the dead from eight columns
Suppose six particles, A to F, whose lives after the movement loop are 0.5, 0.25, 0, 0.75, -0.25, and 1.0. A life at or below zero is dead, so C and E must go, and the survivors must stay in order.
The front-skip. kept starts at 0. The while loop moves past A
(0.5) and B (0.25), and stops at C, whose life is 0. Now kept is 2:
the first two are already where they belong, and nothing copies them.
The compaction loop, from i = 2:
i |
Particle at i |
Alive? | What happens | kept after |
|---|---|---|---|---|
| 2 | C (0) | no | skipped | 2 |
| 3 | D (0.75) | yes | every column: slot 2 = slot 3 | 3 |
| 4 | E (-0.25) | no | skipped | 3 |
| 5 | F (1.0) | yes | every column: slot 3 = slot 5 | 4 |
The cut. Every column is resized to 4, and the columns read A, B,
D, F. Slots 4 and 5 still held E, which is dead, and the old copy of F,
and resize drops them. Because
the lambda in the loop copies slot i to slot kept in all eight
columns, the size and colour of D and F travel with their positions,
even though the loop only tested life_.
The update loop is the payoff. Removing the dead is the price:
std::erase_if on one column cannot do it, because the test is on
life and the other columns would not know which entries went. So the
removal is written by hand, moving every column the same way. Like
std::erase_if, it leaves the particles before the first dead one
where they are; from there on it must move all eight columns.
One allocation per particle
Section titled “One allocation per particle”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One heap allocation per particle, reached through a vector of// pointers. This is what a class hierarchy of particle types pushes// you towards (std::vector<std::unique_ptr<Base>>). It is here to be// measured against the other two, not as a recommendation.class PointerPerParticle {public: // Reserves room for n pointers only; each particle is still allocated // on its own when it is added. void reserve(std::size_t n) { particles_.reserve(n); } // make_unique copies p into a new heap object: one allocation per add. void add(const Particle& p) { particles_.push_back(std::make_unique<Particle>(p)); } void update(float dt);
[[nodiscard]] std::size_t size() const noexcept { return particles_.size(); } // The * follows the pointer; the Particle is then copied out. [[nodiscard]] Particle particle(std::size_t i) const { return *particles_[i]; }
private: // The vector holds only pointers, side by side; the particles they own // are wherever the heap put them, not necessarily near each other. std::vector<std::unique_ptr<Particle>> particles_;};This layout is here to be measured against the other two. It is what a
class hierarchy of particle types pushes you towards, a
std::vector<std::unique_ptr<Base>>, and it has every cost from Step
2: one allocation per particle added, one free per particle removed,
and an update loop that follows a pointer for each particle. The
vector of pointers is contiguous; the particles are not.
If particle types really do behave differently, a vector per type, or
a std::variant of the types stored by value, keeps the data
contiguous while keeping the types apart. Type erasure
shows another way to hold different types by value, and counts its
allocations.
The layouts in memory
Section titled “The layouts in memory”Text description of the diagram
Array of structs: one block of memory holding particle 0’s eight fields (x, y, vx, vy, life, then size, colour, emitter), then particle 1’s eight fields, and so on. Struct of arrays: one block per field; the x column holds x0, x1, x2 and so on, and likewise y, vx, vy, and life, which update reads, and size, colour, and emitter, which update never reads. One allocation per particle: a block of pointers p0, p1, p2 and so on, each pointing to a particle in its own block somewhere else in memory.
Diagram source (Mermaid)
flowchart TB
subgraph AOS["Array of structs: one block"]
direction LR
A0["particle 0: x y vx vy life, then size colour emitter"] --- A1["particle 1: x y vx vy life, then size colour emitter"] --- A2["particle 2 ..."]
end
subgraph SOA["Struct of arrays: one block per field"]
direction TB
X["x column: x0 x1 x2 ..."]
Y["y column: y0 y1 y2 ..."]
L["vx, vy, and life columns, the same way"]
S["size, colour, and emitter columns, never read by update"]
end
subgraph PTR["One allocation per particle"]
direction LR
V["vector of pointers: p0 p1 p2 ..."] --> P0["particle 0, its own block"]
V --> P1["particle 1, somewhere else"]
V --> P2["particle 2, somewhere else"]
end| Question | Array of structs | Struct of arrays | One allocation per particle |
|---|---|---|---|
Allocations to add n, after reserve |
1 | 8, one per column | n + 1 |
| Loop that uses a few fields | Walks the cold fields too | Walks only the columns it uses | Follows a pointer per particle |
| Code that uses a whole particle | Natural | Gathers from eight columns | Natural |
| Adding or removing | One vector | Every column, kept in step by the class | An allocation or a free each time |
| References to a particle stay valid | Until the vector grows or removes | There is no Particle object to refer to |
Yes, until that particle is removed |
| When it fits | The default | Hot loops over many elements that use few fields, once measured | Different types with different behaviour, few in number |
There are layouts in between. Hot/cold splitting keeps a vector of small structs with the hot fields and a parallel vector with the cold ones: two columns instead of eight. Some engines group a fixed number of particles into a small struct of arrays and keep an array of those blocks. Both are the same idea, keeping what the busy loop reads close together, at different costs in code.
Step 5: scratch memory from a memory resource
Section titled “Step 5: scratch memory from a memory resource”Some memory lives for one frame: the list of particles inside a box,
for a collision check, is built, used, and thrown away. A new
std::vector each frame would allocate every frame. A vector kept
between frames and cleared would not, but someone must own it, and a
frame may need many such lists, of different types, each with its own
owner. An arena that every short-lived container in the frame shares,
released at once, needs no long-lived owners. C++17’s
polymorphic memory resources in <memory_resource> let the caller
choose where such a container gets its memory:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The indexes of the particles inside box, in order. The caller chooses// where the list's memory comes from: pass an arena that is reset every// frame, and a query that fits in it never calls the global operator new.// std::pmr::vector is an ordinary vector whose allocator asks a// std::pmr::memory_resource for memory instead of calling new directly.// The resource is passed as a raw pointer because the function does not// own it: the caller must keep it alive for as long as the returned// vector exists. The edges of the box count as inside.[[nodiscard]] std::pmr::vector<std::size_t> inside(const ArrayOfStructs& particles, const Box& box, std::pmr::memory_resource* memory);std::pmr::vector<T>is astd::vectorwhose allocator holds a pointer to astd::pmr::memory_resource. Each allocation is a virtual call on that resource, so the same vector type can take its memory from different places.std::pmr::monotonic_buffer_resourcehands out memory from a buffer it was given, by moving a pointer forward. Freeing does nothing; everything is released at once when the resource is destroyed. Given a buffer on the stack, a query that fits in it never calls the globaloperator new. When the buffer runs out, it asks its upstream resource, by default the default resource when the arena was made, which unless changed isnew_delete_resource(), the globaloperator new, so a big query still works, just more slowly. It is not thread safe.std::pmr::unsynchronized_pool_resourcekeeps pools of fixed-size blocks and reuses freed ones, for containers that grow and shrink;synchronized_pool_resourceis the thread-safe version.
The function takes the resource as a parameter, rather than creating one, because the caller knows how long the memory is needed. That is the same reasoning as injecting a dependency: the function does the work, and the caller decides the policy.
Running it
Section titled “Running it”The demo builds 1000 particles in each layout, runs 64 frames of 1/64 second, adds new particles to replace the dead, and runs one query with a 4 KiB arena on the stack, counting heap allocations at each step:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Fills the three layouts with the same 1000 particles, runs one second// of frames, refills them, and runs one query, printing how many heap// allocations each step made. The counts, not times, are the output, so// it is the same on every run.#include "counting_new.hpp"#include "layouts.hpp"#include "particle.hpp"#include "query.hpp"
#include <array>#include <cstddef>#include <iomanip>#include <iostream>#include <memory_resource>#include <string>
using namespace particles;
namespace {
constexpr std::size_t count = 1000;constexpr float frame = 1.0f / 64; // seconds
// The three helpers below are templates: `Layout` stands for whichever// layout class is passed, and the compiler writes one copy per class.// Each starts an AllocationCounter, does one job, and returns how many// allocations the job made.
// reserve, then add `count` particles.template <typename Layout>std::size_t allocations_to_fill(Layout& layout) { const heap::AllocationCounter counter; layout.reserve(count); for (std::size_t i = 0; i < count; ++i) layout.add(sample_particle(i)); return counter.count();}
// Run `frames` frames of update.template <typename Layout>std::size_t allocations_to_run(Layout& layout, int frames) { const heap::AllocationCounter counter; for (int f = 0; f < frames; ++f) layout.update(frame); return counter.count();}
// Add n more particles, without a reserve first.template <typename Layout>std::size_t allocations_to_add(Layout& layout, std::size_t n) { const heap::AllocationCounter counter; for (std::size_t i = 0; i < n; ++i) layout.add(sample_particle(i)); return counter.count();}
// True if two layouts, of any two types, hold equal particles in the same// order. Particle's == compares every field.template <typename A, typename B>bool same_particles(const A& a, const B& b) { if (a.size() != b.size()) return false; for (std::size_t i = 0; i < a.size(); ++i) { if (a.particle(i) != b.particle(i)) return false; } return true;}
// Prints one table row: the name padded to 29 characters, so the numbers// line up, then the value. std::left and std::setw do the padding.void row(const std::string& name, std::size_t value) { std::cout << " " << std::left << std::setw(29) << name << value << '\n';}
} // namespace
int main() { ArrayOfStructs aos; StructOfArrays soa; PointerPerParticle pointers;
std::cout << count << " particles in three layouts\n"; std::cout << "allocations to add them, after one reserve:\n"; row("array of structs:", allocations_to_fill(aos)); row("struct of arrays:", allocations_to_fill(soa)); row("one allocation per particle:", allocations_to_fill(pointers));
std::cout << "allocations during 64 frames (1 s):\n"; row("array of structs:", allocations_to_run(aos, 64)); row("struct of arrays:", allocations_to_run(soa, 64)); row("one allocation per particle:", allocations_to_run(pointers, 64));
const bool agree = same_particles(aos, soa) && same_particles(aos, pointers); std::cout << "alive after 1 s: " << aos.size() << ", same in every layout: " << (agree ? "yes" : "no") << '\n';
// Top the layouts back up to 1000. The vectors kept their capacity when // particles died, so this tests whether refilling allocates again. const std::size_t refill = count - aos.size(); std::cout << "allocations to add " << refill << " new particles:\n"; row("array of structs:", allocations_to_add(aos, refill)); row("struct of arrays:", allocations_to_add(soa, refill)); row("one allocation per particle:", allocations_to_add(pointers, refill));
// A query whose list lives in a 4 KiB buffer on the stack. // The arena hands out pieces of `buffer` in order and frees nothing // until it is destroyed. It must be declared after `buffer` (so it is // destroyed first) and before `found`, which uses it. std::array<std::byte, 4096> buffer; std::pmr::monotonic_buffer_resource arena(buffer.data(), buffer.size()); const heap::AllocationCounter counter; // Box{left, bottom, right, top}; &arena is the memory resource. const std::pmr::vector<std::size_t> found = inside(aos, Box{0, 0, 4, 2}, &arena); const std::size_t used = counter.count(); std::cout << "particles in the box (0, 0) to (4, 2): " << found.size() << ", allocations with an arena: " << used << '\n';}1000 particles in three layoutsallocations to add them, after one reserve: array of structs: 1 struct of arrays: 8 one allocation per particle: 1001allocations during 64 frames (1 s): array of structs: 0 struct of arrays: 0 one allocation per particle: 0alive after 1 s: 400, same in every layout: yesallocations to add 600 new particles: array of structs: 0 struct of arrays: 0 one allocation per particle: 600particles in the box (0, 0) to (4, 2): 18, allocations with an arena: 0- Adding, after one
reserve: one allocation for the array of structs, eight for the struct of arrays (one per column), and 1001 for one allocation per particle (the vector of pointers, then each particle). - 64 frames: no allocations in any layout. Moving and ageing writes to memory that already exists, and removal never allocates; in the pointer layout it frees each dead particle.
- Alive after 1 s: lives run from 0.5 to 1.5 seconds in quarter seconds, so the three shortest of the five lives, 600 particles in all, have run out, and the 400 left are the same in every layout. The sample values are sums of powers of two, so the arithmetic is exact and the comparison can be exact too.
- Adding 600 new particles: none for the two vector layouts, because removing elements kept their capacity; 600 for one allocation per particle. This is R2 and R4 in one line: in a game that adds and removes particles every frame, only the third layout allocates every frame.
- The query found 18 particles: 15 of the new ones, at their starting points, and 3 survivors that moved into the box. It made no heap allocation: the list fitted in the arena.
Measuring it yourself
Section titled “Measuring it yourself”The benchmark program times 100 frames of update for each layout,
following the rules of Step 1:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Times 100 frames of update for each layout. Not a test: the numbers// depend on the machine, the compiler, the build type, and what else is// running. Build with -DCMAKE_BUILD_TYPE=Release before reading them;// a Debug build measures the debug checks, not the layout.//// Usage: adv_particles_bench [particles] [runs]#include "layouts.hpp"#include "particle.hpp"
#include <algorithm>#include <chrono>#include <cstddef>#include <cstdlib>#include <iomanip>#include <iostream>#include <string>#include <vector>
using namespace particles;
namespace {
constexpr int frames = 100;constexpr float frame = 1.0f / 1024; // short, so nothing dies
// Builds a layout of n particles. Returned by value: the vectors inside// are moved out (or the copy is skipped entirely), not copied.template <typename Layout>Layout make(std::size_t n) { Layout layout; layout.reserve(n); for (std::size_t i = 0; i < n; ++i) layout.add(sample_particle(i)); return layout;}
// The sum of every x, printed so that the compiler cannot drop the// updates as unused.template <typename Layout>double checksum(const Layout& layout) { double sum = 0; for (std::size_t i = 0; i < layout.size(); ++i) sum += layout.particle(i).x; return sum;}
// The median time of `runs` runs. Each run starts from fresh particles// built outside the timed part, so only update is measured.// The median is used, not the average, because one slow run (another// program woke up, say) would pull an average up but barely moves the// middle value.template <typename Layout>void time_layout(const std::string& name, std::size_t n, int runs) { std::vector<double> microseconds; double sum = 0; for (int r = 0; r < runs; ++r) { Layout layout = make<Layout>(n); // not timed // steady_clock never jumps, so stop - start is a true interval. const auto start = std::chrono::steady_clock::now(); for (int f = 0; f < frames; ++f) layout.update(frame); const auto stop = std::chrono::steady_clock::now(); // duration<double, std::micro> is a duration counted in // microseconds as a double, so fractions are kept. microseconds.push_back(std::chrono::duration<double, std::micro>(stop - start).count()); sum += checksum(layout); // after `stop`, so it is not timed either } // Sorted, the middle element is the median. std::sort(microseconds.begin(), microseconds.end()); // With an even number of runs this is the upper of the two middle values. std::cout << name << ": median " << microseconds[microseconds.size() / 2] << " us for " << frames << " frames (checksum " << std::setprecision(17) << sum << std::setprecision(6) << ")\n";}
} // namespace
// argc is how many words were on the command line, including the program// name; argv[1] and argv[2] are the optional arguments, as text.int main(int argc, char** argv) { // strtoul and atoi turn text into numbers. Text with no number at its // start, such as "abc", gives 0, which the check below refuses. const std::size_t n = argc > 1 ? std::strtoul(argv[1], nullptr, 10) : 100'000; const int runs = argc > 2 ? std::atoi(argv[2]) : 11; if (n == 0 || runs <= 0) { std::cerr << "usage: adv_particles_bench [particles] [runs]\n"; return 2; } std::cout << n << " particles, " << runs << " runs each\n"; // The <...> names the layout to time; each call builds and times that class. time_layout<ArrayOfStructs>("array of structs", n, runs); time_layout<StructOfArrays>("struct of arrays", n, runs); time_layout<PointerPerParticle>("one allocation per particle", n, runs);}To run it, configure an optimized build in its own directory, from the
examples directory:
cmake -S . -B build/release -DCMAKE_BUILD_TYPE=Releasecmake --build build/release --target adv_particles_benchbuild/release/advanced/performance/particles/adv_particles_bench 100000 11This page shows no numbers from it, and that is deliberate. Try it with 1000 particles and with a few million: below the size of the caches, the layouts may differ little, and above it, how much each layout reads from memory starts to matter. Some things to expect, and to check rather than believe:
- A fresh benchmark flatters the pointer layout. Its particles were allocated one after another, so the allocator may have put them next to each other. In a game that has been adding and removing particles for an hour, they are scattered. A fair test churns first.
- The struct of arrays is not always faster. With few particles, or with a loop that uses most fields, gathering from eight columns can cost more than it saves.
- The checksum must match between layouts and between runs with the same arguments. If it does not, the benchmark is measuring different work.
- Repeat on the target. A result from a desktop says little about a phone or a console.
The build runs the benchmark only as a smoke test, with 1000 particles and 3 runs, to check that it still builds and finishes. Nothing checks its timings.
Testing
Section titled “Testing”Speed is measured; correctness and allocation counts are tested.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The layouts are three representations of one thing, so after the same// frames they must hold the same particles in the same order.//// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_EQ(actual, expected) does the// same for an equality and prints both values when they differ. They// come from the site's small test header, lld_test.hpp.//// filled<Layout>(n) and contents(layout) are helpers earlier in this// file: the first adds sample particles 0 to n - 1 to a new layout, the// second copies a layout's particles out into a std::vector<Particle>.// Comparing two such vectors with == compares every field of every// particle, in order.LLD_TEST(the_three_layouts_agree_frame_by_frame) { ArrayOfStructs aos = filled<ArrayOfStructs>(1000); StructOfArrays soa = filled<StructOfArrays>(1000); PointerPerParticle pointers = filled<PointerPerParticle>(1000); // Checked after every frame, not only at the end, so a difference is // caught in the frame that caused it. for (int f = 0; f < 100; ++f) { aos.update(frame); soa.update(frame); pointers.update(frame); LLD_CHECK(contents(soa) == contents(aos)); LLD_CHECK(contents(pointers) == contents(aos)); } // 100 frames of 1/64 s is 1.5625 s, so this also proves removal ran. LLD_CHECK_EQ(aos.size(), std::size_t{0}); // every life is at most 1.5 s}- The three layouts agree frame by frame: same particles, same order, same values, for 100 frames until every particle has died. That is R5, and it is what makes a layout change safe to try. Other tests check the update arithmetic, removal at exactly zero life, and that removal keeps every field of the survivors, including the cold columns a careless compaction would forget.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Each test counts with heap::AllocationCounter, which measures from the// line that creates it. add_samples(layout, n), a helper earlier in this// file, adds sample particles 0 to n - 1.
// Proves the cost of filling each layout after one reserve: one vector// allocates once, eight columns allocate eight times, and one allocation// per particle adds one for each particle. The counter is never reset,// so each check adds to the expected total of the one before.LLD_TEST(after_one_reserve_adding_allocates_once_per_vector) { ArrayOfStructs aos; StructOfArrays soa; PointerPerParticle pointers; const heap::AllocationCounter counter; aos.reserve(500); add_samples(aos, 500); LLD_CHECK_EQ(counter.count(), std::size_t{1}); soa.reserve(500); add_samples(soa, 500); LLD_CHECK_EQ(counter.count(), std::size_t{1 + 8}); // one per column pointers.reserve(500); add_samples(pointers, 500); // The pointer vector itself, then one make_unique per particle. LLD_CHECK_EQ(counter.count(), std::size_t{1 + 8 + 1 + 500});}
// The exact count depends on the standard library's growth factor, so// this checks only that growth happens a few times, not once per add.LLD_TEST(without_reserve_the_vector_grows_a_few_times) { ArrayOfStructs aos; const heap::AllocationCounter counter; add_samples(aos, 1000); LLD_CHECK(counter.count() > 1); LLD_CHECK(counter.count() < 50);}
// Proves that 64 frames of update, including removing the dead, allocate// nothing in any layout: moving numbers and shrinking vectors never asks// for memory. The counter starts after the particles were added.LLD_TEST(frames_allocate_nothing) { ArrayOfStructs aos; StructOfArrays soa; PointerPerParticle pointers; add_samples(aos, 1000); add_samples(soa, 1000); add_samples(pointers, 1000); const heap::AllocationCounter counter; for (int f = 0; f < 64; ++f) { aos.update(frame); soa.update(frame); pointers.update(frame); } LLD_CHECK_EQ(counter.count(), std::size_t{0});}
// Removing particles keeps a vector's capacity, so refilling the same// number reuses it. Only the layout with one allocation per particle// pays again for every new particle.LLD_TEST(refilling_after_deaths_reuses_capacity) { ArrayOfStructs aos; StructOfArrays soa; PointerPerParticle pointers; add_samples(aos, 1000); add_samples(soa, 1000); add_samples(pointers, 1000); for (int f = 0; f < 64; ++f) { aos.update(frame); soa.update(frame); pointers.update(frame); } const std::size_t refill = 1000 - aos.size(); LLD_CHECK(refill > 0); // some did die, or the test would prove nothing
const heap::AllocationCounter counter; add_samples(aos, refill); add_samples(soa, refill); LLD_CHECK_EQ(counter.count(), std::size_t{0}); // The pointer vector also has room, but each new particle is a new // heap object: exactly one allocation each. add_samples(pointers, refill); LLD_CHECK_EQ(counter.count(), refill);}- Allocation counts are exact where the standard fixes them: one
allocation after
reserve, eight for eight columns, zero during frames, zero to refill reserved capacity. That is R4 as a test that fails the day someone adds an allocation toupdate. - Where the standard does not fix the count, the test does not
either. How often a vector grows without
reservedepends on the library’s growth factor, so that test checks only “more than once, and far fewer than once per element”.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A full StructOfArrays must grow all eight columns to add one more// particle. Make each of those eight allocations fail in turn: every// time, the particles must be unchanged and the columns still in step,// so the next add works.//// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception. heap::fail_after(n) lets n more allocations// succeed and makes the one after fail with std::bad_alloc, so fail_at 0// fails the first column's reserve and fail_at 7 the last one's.LLD_TEST(a_failed_add_leaves_the_columns_in_step) { for (int fail_at = 0; fail_at < 8; ++fail_at) { // A fresh, full object each time round: 4 particles in columns // that can hold exactly 4, so the fifth add must allocate. StructOfArrays soa; soa.reserve(4); // GCC's library gives exactly 4; elsewhere this test fails loudly add_samples(soa, 4); const std::vector<Particle> before = contents(soa);
heap::fail_after(fail_at); LLD_CHECK_THROWS(soa.add(sample_particle(4)), std::bad_alloc); // A failure resets itself, but if no allocation failed (which the // check above reports), this stops it from hitting a later one. heap::stop_failing();
// The failed add changed nothing that can be seen, and the object // still works: the same add now succeeds. LLD_CHECK_EQ(soa.size(), std::size_t{4}); LLD_CHECK(contents(soa) == before); soa.add(sample_particle(4)); LLD_CHECK_EQ(soa.size(), std::size_t{5}); LLD_CHECK(soa.particle(4) == sample_particle(4)); }}- A failed
addleaves the columns in step. The test fills a struct of arrays to capacity, so the nextaddmust grow all eight columns, then makes each of those eight allocations fail in turn. Each time, the particles must be unchanged and the nextaddmust work. To check that the test can fail, the reserve-first loop was removed fromaddin a copy of the example: the test then failed 21 checks, starting with a size of 5 where 4 was expected.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Proves that a query whose result fits in a 4 KiB stack buffer makes no// heap allocation at all: the pmr vector's memory all comes from the// arena. 15 indexes, even with the vector's growth along the way, need// far less than 4096 bytes.LLD_TEST(a_query_that_fits_in_the_arena_allocates_nothing) { ArrayOfStructs aos; add_samples(aos, 1000); std::array<std::byte, 4096> buffer; std::pmr::monotonic_buffer_resource arena(buffer.data(), buffer.size()); const heap::AllocationCounter counter; const std::pmr::vector<std::size_t> found = inside(aos, Box{0, 0, 4, 2}, &arena); LLD_CHECK_EQ(counter.count(), std::size_t{0}); LLD_CHECK_EQ(found.size(), std::size_t{15}); // x 0 to 4, y 0 to 2}
// When the buffer runs out, the arena asks its upstream resource, which// by default is the global operator new. The query still works.LLD_TEST(a_query_too_big_for_the_arena_falls_back_to_the_heap) { ArrayOfStructs aos; add_samples(aos, 1000); std::array<std::byte, 64> buffer; // room for at most 8 indexes of 8 bytes (64-bit) std::pmr::monotonic_buffer_resource arena(buffer.data(), buffer.size()); const heap::AllocationCounter counter; const std::pmr::vector<std::size_t> found = inside(aos, Box{0, 0, 39, 24}, &arena); LLD_CHECK(counter.count() > 0); LLD_CHECK_EQ(found.size(), std::size_t{1000});}- The arena tests check both sides: a query that fits allocates nothing, and a query far bigger than a 64-byte buffer still returns every particle, with the extra memory coming from the heap. The second test is the one that exposed the counter’s missing aligned form.
The tests run with GCC and Clang and under AddressSanitizer and
UndefinedBehaviorSanitizer. In the tsan build, only the layout tests
and the benchmark smoke test are built and run (with ctest --test-dir build/tsan; the tsan test preset runs only the concurrency tests),
because the allocation tests and the demo replace operator new.
The design at a glance
Section titled “The design at a glance”struct particles::Particle
plain data, no invariant
Member functions
float x, y, vx, vy, life;read by updatefloat size;cold: drawing datastd::uint32_t colour, emitter;cold
class particles::ArrayOfStructs
the default
Data members
std::vector<Particle> particles_;
Member functions
void reserve(std::size_t n);void add(const Particle& p);void update(float dt);moves, ages, removes the dead in orderstd::size_t size() const noexcept;Particle particle(std::size_t i) const;i less than size()std::span<const Particle> all() const noexcept;
class particles::StructOfArrays
invariant: all columns the same length
Data members
void for_each_column(F f);template: the one list of columnsstd::vector<float> x_, y_, vx_, vy_, life_, size_;std::vector<std::uint32_t> colour_, emitter_;
Member functions
void reserve(std::size_t n);void add(const Particle& p);strong guarantee: makes room in every column firstvoid update(float dt);std::size_t size() const noexcept;Particle particle(std::size_t i) const;gathered from eight columns
class particles::PointerPerParticle
for comparison: one allocation per particle
Data members
std::vector<std::unique_ptr<Particle>> particles_;
Member functions
void add(const Particle& p);void update(float dt);
namespace particles
Functions
std::pmr::vector<std::size_t> inside(const ArrayOfStructs& particles, const Box& box, std::pmr::memory_resource* memory);caller picks the memory
namespace heap
links only into the demo and allocation tests
Functions
std::size_t allocations() noexcept;calls to the global operator new so farvoid fail_after(int n) noexcept;tests: fail one later allocation
When to change the layout, and when not to
Section titled “When to change the layout, and when not to”Change the layout when all of these hold:
- A measurement on the target shows the loop over budget, and a profile shows the time is in walking the data.
- There are many elements, typically thousands or more, walked together, often every frame or every request.
- The hot loop uses a minority of the fields.
- The tests can prove the new layout gives the same results.
Keep the array of structs, or keep whatever is simplest, when:
- The code is not hot. Most of a program, such as configuration, user interface logic, and the business rules of an order, runs too rarely for layout to matter. A struct of arrays there is cost without benefit.
- Code mostly uses whole objects, or picks single elements by key. Gathering eight columns for each object is slower and harder to read.
- Objects need stable identity. Other code holds references to them, or they have behaviour and invariants of their own. A struct of arrays has no object to hold a reference to.
- Nobody has measured. Then the change is a guess with a certain cost.
Common mistakes
Section titled “Common mistakes”- Timing a Debug build. It measures the debug checks, and the ranking of two designs can be different in an optimized build.
- Benchmarking one run, or code whose result is unused. One run measures noise; unused results may be removed by the optimizer.
- Allocating in the loop that runs every frame: a vector or string
created inside it, a
std::make_uniqueper event, astd::functionholding a large capture. Count, then hoist or reuse. - Forgetting
reservewhen the size is known, or callingreserve(size() + 1)before every add, which defeats the vector’s doubling: every add then reallocates and copies every element, so adding n elements copies on the order of n² elements. - A struct of public vectors. The invariant that the columns stay in step needs a class that owns them.
- Holding a reference or pointer into a vector that may grow. Growth moves every element. See Containers and complexity basics.
- An arena that dies before its containers, or copying a
std::pmr::vectorand expecting the copy to use the same arena. - Optimizing what the profile did not point at. The time is often not where you expect.
When the requirements change
Section titled “When the requirements change”- “Particles come in kinds that behave differently.” Do not reach
for
std::vector<std::unique_ptr<ParticleBase>>by habit; that is the third layout. Keep one container per kind, or store astd::variantof the kinds by value, and measure if the kinds are many. - “Update on several threads.” Contiguous layouts split well into ranges, one per thread. Make sure threads do not write to the same cache line, which slows them down even when they write different variables (false sharing), and see Asynchronous work, cancellation, and shutdown for a worker pool to run the work.
- “Other systems keep handles to particles.” Removal moves particles, so an index stops naming the same particle. A handle that pairs a slot index with a generation number, checked on each use, survives removal; Ownership graphs and lifetime design mentions this kind of checked handle.
- “The renderer needs every field.” Then the renderer favours the array of structs, and the update favours the struct of arrays. Measure both together; a hot/cold split may serve both.
Exercise
Section titled “Exercise”Exercise: Identify allocation hotspots
This function builds one report line per order. It runs for every page view, with a few hundred orders, and a profile shows it near the top. Find every place it allocates more than it needs to, say why, and rewrite it. Then say how you would check your rewrite.
This code was compiled with GCC 11.4 and Clang 14 and run, with the example’s allocation counter, in a scratch program; it is not part of the example tree.
struct Order { std::string customer; std::vector<std::string> items;};
// Returns one line per order, such as "customer ada: pen ink".std::vector<std::string> report(const std::vector<Order>& orders) { std::vector<std::string> lines; for (Order order : orders) { std::string line = "customer " + order.customer + ":"; for (std::string item : order.items) { line = line + " " + item; } lines.push_back(line); } return lines;}Show the explained answer
for (Order order : orders)copies each order: its customer string, its vector, and every item string in it. Loop byconst Order&.for (std::string item : order.items)copies each item again. Loop byconst std::string&.line = line + " " + itembuilds a new string fromlineand the space, then assigns it, for every item, so the line is copied in full each time and the work grows with the square of its length. Append with+=."customer " + order.customer + ":"builds the start of the line through temporaries. The library reuses the first one’s buffer, so here it costs one allocation, but building the whole line in one string reserved once removes all the regrowth.lines.push_back(line)copies the finished line. Move it in:lineis not used again.linesgrows several times. Its final size is known:reserve(orders.size()).
The rewrite was compiled and run in the same scratch program:
std::vector<std::string> report(const std::vector<Order>& orders) { std::vector<std::string> lines; lines.reserve(orders.size()); // one line per order: allocate once for (const Order& order : orders) { // a reference: no copy of the order // Work out the line's final length first, so it can be allocated // once: 9 for "customer ", the name, 1 for ':', then 1 + the // length of each item for the space and the item. std::size_t length = 9 + order.customer.size() + 1; // "customer " and ':' for (const std::string& item : order.items) length += 1 + item.size(); std::string line; line.reserve(length); // after this, the += calls below never allocate line += "customer "; line += order.customer; line += ':'; for (const std::string& item : order.items) { line += ' '; line += item; } // Move, not copy: the vector takes over line's buffer, and `line` // is not used again. lines.push_back(std::move(line)); } return lines;}How to check it. First, that the output is the same: compare the
two versions’ results on the same orders. Then count: with 100 orders
of 5 items each, and names long enough not to fit in a string’s small
buffer, the scratch program counted 2408 allocations for the original
and 101 for the rewrite, one for lines and one per line, with both
compilers and GCC 11’s standard library. The exact numbers depend on
the library’s small-string size and growth policy; the shape of the
change does not. Finally, time it in an optimized build, and keep the
rewrite only if the page views got faster.
Returning lines by value is not a hotspot: the vector is moved
or constructed in place, not copied.
Summary
Section titled “Summary”- Measure first, in an optimized build, against a stated budget. Change one thing at a time, and keep a change only if the measurement and the tests agree.
- Allocation costs time, adds jitter, and scatters data. Count it
in tests, and remove it from hot loops with
reserve, reused capacity, and storage by value. - Contiguous memory walked in order has good cache locality; data reached through a pointer per element does not.
- Array of structs is the default. Struct of arrays helps loops over many elements that use few fields, and costs a class whose invariant keeps the columns in step.
- Memory resources let the caller choose where memory comes from, such as an arena per frame, and bring lifetime rules with them.
- This page gives no timings, because a timing is a fact about one machine; the tests check what is true everywhere.