Why allocation is expensive
new T calls operator new, which usually calls malloc. A general-purpose allocator must handle any size, from any thread, in any order of frees, so each call does real work: find a size class, take a block from a per-thread or global free list (possibly with an atomic operation or lock), occasionally ask the operating system for more pages (a system call and page faults), and on free possibly coalesce or return memory to another thread's cache. The average cost is tens of nanoseconds; the tail includes page faults and system calls measured in microseconds. Freshly allocated memory is also often cold in cache.
A trading hot path that allocates per message therefore pays both a steady cost and unpredictable latency spikes. The goal of this lesson is to remove allocations from the hot path and to prove that you did.
Step 1: count allocations
You cannot fix what you have not measured. Replacing the global operator new with a counting version is a cheap way to see every allocation (production code would use a profiler or a debug-only hook, but the idea is the same).
#include <cstdio>
#include <cstdlib>
#include <new>
#include <string>
#include <vector>
static long g_allocs = 0;
void* operator new(std::size_t n) {
++g_allocs;
if (void* p = std::malloc(n)) return p;
throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }
template <class F>
long count_allocs(F&& f) {
long before = g_allocs;
f();
return g_allocs - before;
}
int main() {
std::printf("1000 push_backs, no reserve: %ld allocations\n", count_allocs([] {
std::vector<int> v;
for (int i = 0; i < 1000; ++i) v.push_back(i);
}));
std::printf("1000 push_backs, reserve: %ld allocation\n", count_allocs([] {
std::vector<int> v;
v.reserve(1000);
for (int i = 0; i < 1000; ++i) v.push_back(i);
}));
std::printf("string of 22 chars: %ld allocations\n",
count_allocs([] { std::string s(22, 'x'); }));
std::printf("string of 23 chars: %ld allocation\n",
count_allocs([] { std::string s(23, 'x'); }));
std::vector<double> scratch;
scratch.reserve(4096); // warm-up: allocate once, outside the hot path
long hot = count_allocs([&] {
for (int tick = 0; tick < 100000; ++tick) {
scratch.clear(); // keeps capacity
for (int i = 0; i < 100; ++i) scratch.push_back(tick * 0.5 + i);
}
});
std::printf("hot loop reusing a buffer: %ld allocations\n", hot);
}
1000 push_backs, no reserve: 11 allocations
1000 push_backs, reserve: 1 allocation
string of 22 chars: 0 allocations
string of 23 chars: 1 allocation
hot loop reusing a buffer: 0 allocations
- Growth: capacities 1, 2, 4, …, 1024 are allocations;
reservemakes it one. - Small string optimisation (SSO): short strings live inside the
std::stringobject itself. The threshold is implementation-specific: 22 characters in libc++ (used here), 15 in libstdc++ and MSVC. Building symbol keys by concatenation can cross it without anyone noticing. - Reuse:
clear()destroys the elements but keeps the capacity, so a buffer allocated once at start-up serves every tick. 100,000 ticks, zero allocations.
Step 2: pools and arenas
When the hot path genuinely needs new objects (orders, book levels, messages), replace the general allocator with one that exploits what you know.
Fixed-size object pool. Every object has the same size, so allocation is popping a slot off a free list and deallocation is pushing it back. The free list is intrusive: a free slot's own bytes store the pointer to the next free slot, so it needs no extra memory.
#include <chrono>
#include <cstddef>
#include <cstdio>
#include <list>
#include <memory_resource>
#include <new>
#include <vector>
struct Order {
long id;
double price;
int qty;
};
// Fixed-capacity pool: one up-front allocation, O(1) acquire/release via an intrusive free list.
template <class T>
class Pool {
union Slot {
Slot* next;
alignas(T) std::byte storage[sizeof(T)];
};
std::vector<Slot> slots_;
Slot* free_ = nullptr;
public:
explicit Pool(std::size_t n) : slots_(n) {
for (std::size_t i = 0; i < n; ++i) {
slots_[i].next = free_;
free_ = &slots_[i];
}
}
template <class... Args>
T* acquire(Args&&... args) {
if (!free_) return nullptr; // caller decides: reject, or fall back to the heap
Slot* s = free_;
free_ = s->next;
return ::new (s->storage) T{std::forward<Args>(args)...};
}
void release(T* p) noexcept {
p->~T();
Slot* s = reinterpret_cast<Slot*>(p);
s->next = free_;
free_ = s;
}
};
using clk = std::chrono::steady_clock;
static double ns_since(clk::time_point t0, long n) {
return std::chrono::duration<double, std::nano>(clk::now() - t0).count() / n;
}
int main() {
constexpr long N = 20'000'000;
constexpr int LIVE = 64; // keep 64 orders alive at a time, recycle in FIFO order
Order* ring[LIVE] = {};
long sink = 0;
auto t0 = clk::now();
for (long i = 0; i < N; ++i) {
Order*& slot = ring[i % LIVE];
delete slot;
slot = new Order{i, 100.0, 1};
sink += slot->id;
}
double heap = ns_since(t0, N);
for (auto*& p : ring) { delete p; p = nullptr; }
Pool<Order> pool(LIVE);
t0 = clk::now();
for (long i = 0; i < N; ++i) {
Order*& slot = ring[i % LIVE];
if (slot) pool.release(slot);
slot = pool.acquire(i, 100.0, 1);
sink += slot->id;
}
double pooled = ns_since(t0, N);
std::printf("new/delete: %.1f ns per order pool: %.1f ns per order (sink %ld)\n",
heap, pooled, sink % 1000);
// std::list with the default allocator vs a monotonic arena.
constexpr int M = 1'000'000;
for (int rep = 0; rep < 2; ++rep) {
t0 = clk::now();
{
std::list<int> l;
for (int i = 0; i < M; ++i) l.push_back(i);
}
double def = ns_since(t0, M);
std::vector<std::byte> arena(M * 32);
t0 = clk::now();
{
std::pmr::monotonic_buffer_resource mbr(arena.data(), arena.size(),
std::pmr::null_memory_resource());
std::pmr::list<int> l(&mbr);
for (int i = 0; i < M; ++i) l.push_back(i);
}
double mono = ns_since(t0, M);
std::printf("std::list push_back+destroy: default %.1f ns/node pmr monotonic %.1f ns/node\n",
def, mono);
}
}
One run on an Apple M1 (macOS system allocator):
new/delete: 41.8 ns per order pool: 1.0 ns per order (sink 0)
std::list push_back+destroy: default 39.2 ns/node pmr monotonic 9.1 ns/node
std::list push_back+destroy: default 74.8 ns/node pmr monotonic 11.1 ns/node
These numbers are machine-specific, and they are noisy: across three runs (six measurements) the default-allocator list ranged from about 38 to 75 ns per node and the arena from 4 to 11 ns, while new/delete stayed at 38 to 42 ns and the pool at about 1 ns. A faster allocator such as jemalloc or glibc's per-thread caches would narrow the gap, but the shape (an order of magnitude) is typical. Note the noise itself: the general allocator's cost varies between runs, the pool's does not.
Arena (monotonic) allocator. std::pmr::monotonic_buffer_resource hands out memory by bumping a pointer through a buffer and never frees individual blocks; everything is released at once when the resource is destroyed. Perfect for per-message or per-request scratch data with a clear end. Here the arena is a pre-allocated buffer with null_memory_resource() as upstream, so exhausting it throws std::bad_alloc instead of silently falling back to the heap: a loud failure is what you want on a hot path.
The std::pmr containers (std::pmr::vector, std::pmr::string, std::pmr::unordered_map, …) take a memory_resource* at run time, so changing allocation strategy does not change the container's type. The cost is a virtual call per allocation and one extra pointer per container. Other resources: unsynchronized_pool_resource (size-class pools, single thread) and synchronized_pool_resource (thread-safe).
Worked example
what do allocations cost a feed handler?
A market-data handler processes messages per second on one core. Each message currently triggers three heap allocations (a std::string symbol key above the SSO limit, a std::vector of levels built without reserve, and a shared_ptr event created with new). Using about 40 ns per allocation-and-free (this machine's figure), estimate the share of the core spent in the allocator, and list the fixes.
Show solutionHide solution
Allocator time per second is
so about 12% of the core, before counting cache misses on freshly allocated memory or tail spikes from page faults. Since a burst can be ten times the average rate, it is worse exactly when it matters.
Fixes, one per allocation:
- Symbol key: intern symbols at start-up into a fixed table and use an integer id (or a
std::string_viewinto a stable buffer) on the hot path. - Levels vector: keep one buffer per handler,
reservethe maximum depth at start-up,clear()per message. - Event object: take it from a pool sized to the maximum in-flight count, or pass a reference into a pre-allocated ring buffer slot.
Then verify with an allocation counter or profiler that the steady-state message loop performs zero allocations, as the "hot loop reusing a buffer" line above does.
Knowledge check
What does std::vector::clear() do to the vector's capacity?
Knowledge check
Which property defines a monotonic (arena) allocator such as std::pmr::monotonic_buffer_resource?
Knowledge check
In libc++, std::string s = sym + "." + venue; produces a 9-character result. How many heap allocations does s itself need?
Key takeaways
- A general allocator costs tens of nanoseconds on average and much more in the tail; on this machine new/delete measured about 40 ns per object.
- First count allocations, then remove them:
reserve, reuse buffers withclear(), rely on SSO for short strings, intern keys. - Fixed-size pools make allocation a free-list pop (about 1 ns here); arenas (
std::pmr::monotonic_buffer_resource) make it a pointer bump and free everything at once. - Pre-allocate at start-up, fail loudly on exhaustion (
null_memory_resourceupstream), and verify that the steady-state loop allocates nothing.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).