Clean algorithms do not guarantee fast C++ code. When a program stutters, the bottleneck is often how it asks for memory. Every call to new or std::make_unique sends the general-purpose allocator hunting for a free block, updating internal metadata, and acquiring locks. Do that 50,000 times per frame, and your frame budget evaporates.
Writing your own allocator sounds intimidating, like kernel work. It is not. With about 80 lines of modern C++20, you can build an Arena allocator and a Pool allocator that keep objects packed tightly in memory for the CPU cache.
Why Standard Heap Allocation Slows You Down
General-purpose allocators like malloc and new have a hard job. They must serve any size request in any order, from 16 bytes to 16 megabytes. That flexibility comes with two steep costs:
- Allocation overhead: Traversing free lists, synchronizing threads with locks, and requesting OS pages via
mmaporbrkcan burn 50 to 200+ CPU cycles per call. - CPU cache misses: CPUs fetch RAM in 64-byte chunks called cache lines, not individual bytes. An L1 cache hit takes roughly 1 nanosecond (about 4 cycles), while a trip to main RAM stalls the CPU for 60 to 100 nanoseconds. Standard heap allocations scatter small objects across memory, forcing constant RAM fetches during loops.
Custom allocators flip that model. You reserve one large, contiguous block up front and slice it yourself:
- Arena (Linear) Allocator: Advances a single offset pointer for every allocation. Individual frees are not supported; instead, you wipe the entire arena in O(1) time by resetting the offset to zero. This fits per-frame game state or per-request HTTP buffers.
- Pool Allocator: Divides a contiguous buffer into fixed-size slots. An internal free list lets you allocate and free single objects in O(1) time with zero fragmentation.
Setting Up Your C++20 Environment
No third-party dependencies are required here. Grab a C++20 compiler with parenthesized aggregate initialization support (GCC 11+ or Clang 16+) and Linux perf if you want hardware cache metrics.
Check your compiler version and create the project files:
g++ --version
mkdir cpp-custom-allocators && cd cpp-custom-allocators
touch allocators.hpp main.cpp
On Ubuntu or Debian, install perf so you can measure L1 cache misses later:
sudo apt update && sudo apt install -y linux-tools-common linux-tools-generic
Implementing Arena and Pool Allocators
Both allocators will live in allocators.hpp. We will lean on C++20 primitives like std::byte, std::align, and std::construct_at to keep the pointer math safe and explicit.
Step 1: Building a Linear Arena Allocator
An Arena owns one raw byte buffer. On each request, it aligns the current pointer to the type’s boundary, bumps the offset forward, and constructs the object in place. Proper alignment matters: unaligned reads slow down the CPU and trigger undefined behavior in C++.
#pragma once
#include <algorithm>
#include <cstddef>
#include <memory>
#include <new>
#include <utility>
class ArenaAllocator {
public:
explicit ArenaAllocator(std::size_t capacity_bytes)
: capacity_(capacity_bytes),
buffer_(static_cast<std::byte*>(::operator new(capacity_bytes))) {}
~ArenaAllocator() {
::operator delete(buffer_);
}
ArenaAllocator(const ArenaAllocator&) = delete;
ArenaAllocator& operator=(const ArenaAllocator&) = delete;
template <typename T, typename... Args>
T* create(Args&&... args) {
void* current_ptr = buffer_ + offset_;
std::size_t space = capacity_ - offset_;
void* aligned_ptr = std::align(alignof(T), sizeof(T), current_ptr, space);
if (!aligned_ptr) {
throw std::bad_alloc();
}
offset_ = static_cast<std::byte*>(aligned_ptr) - buffer_ + sizeof(T);
return std::construct_at(static_cast<T*>(aligned_ptr), std::forward<Args>(args)...);
}
void reset() noexcept {
offset_ = 0;
}
private:
std::size_t capacity_;
std::size_t offset_ = 0;
std::byte* buffer_;
};
Look at reset(). Flipping offset_ back to 0 reclaims megabytes of memory in a single CPU instruction. One catch: reset() skips destructors, so either stick to trivially destructible types or invoke destructors manually before resetting.
Step 2: Building a Fixed-Size Pool Allocator
Arenas fall short when objects have mixed lifetimes and must be freed out of order. A Pool allocator handles that case without external tracking arrays. Each unused slot stores a pointer to the next free slot right inside its own raw bytes—a pattern called an intrusive free list.
template <typename T>
class PoolAllocator {
static_assert(sizeof(T) >= sizeof(void*), "T must be at least pointer-sized");
struct FreeNode {
FreeNode* next;
};
public:
explicit PoolAllocator(std::size_t max_objects)
: capacity_(max_objects) {
constexpr std::size_t slot_align = std::max(alignof(T), alignof(FreeNode));
slot_size_ = (sizeof(T) + slot_align - 1) & ~(slot_align - 1);
buffer_ = static_cast<std::byte*>(::operator new(slot_size_ * capacity_, std::align_val_t{slot_align}));
// Link all slots into the initial free list
for (std::size_t i = 0; i < capacity_; ++i) {
auto* node = reinterpret_cast<FreeNode*>(buffer_ + i * slot_size_);
node->next = free_head_;
free_head_ = node;
}
}
~PoolAllocator() {
constexpr std::size_t slot_align = std::max(alignof(T), alignof(FreeNode));
::operator delete(buffer_, std::align_val_t{slot_align});
}
PoolAllocator(const PoolAllocator&) = delete;
PoolAllocator& operator=(const PoolAllocator&) = delete;
template <typename... Args>
T* create(Args&&... args) {
if (!free_head_) {
throw std::bad_alloc();
}
FreeNode* node = free_head_;
free_head_ = node->next;
return std::construct_at(reinterpret_cast<T*>(node), std::forward<Args>(args)...);
}
void destroy(T* ptr) noexcept {
if (!ptr) return;
std::destroy_at(ptr);
auto* node = reinterpret_cast<FreeNode*>(ptr);
node->next = free_head_;
free_head_ = node;
}
private:
std::size_t capacity_;
std::size_t slot_size_;
std::byte* buffer_;
FreeNode* free_head_ = nullptr;
};
Allocating pops the head of the free list; destroying calls the destructor and pushes the slot back onto the head. Because every slot sits inside one contiguous array, scanning active objects streams smoothly through L1 and L2 cache lines.
Benchmarking and Checking CPU Cache Hits
Never trust an optimization on gut feeling alone. Let us benchmark one million 24-byte Particle structs in main.cpp, comparing standard new/delete against both custom allocators.
Step 1: Writing a Practical Benchmark
#include "allocators.hpp"
#include <chrono>
#include <iostream>
#include <vector>
struct Particle {
float x, y, z;
float vx, vy, vz;
};
int main() {
constexpr std::size_t count = 1'000'000;
// 1. Standard Heap
std::vector<Particle*> heap_ptrs(count);
auto start = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < count; ++i) {
heap_ptrs[i] = new Particle{1.0f, 2.0f, 3.0f, 0.1f, 0.2f, 0.3f};
}
double heap_sum = 0;
for (Particle* p : heap_ptrs) heap_sum += p->x;
for (Particle* p : heap_ptrs) delete p;
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Standard new/delete: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms (sum=" << heap_sum << ")\n";
// 2. Arena Allocator
ArenaAllocator arena(count * sizeof(Particle) + 1024);
std::vector<Particle*> arena_ptrs(count);
start = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < count; ++i) {
arena_ptrs[i] = arena.create<Particle>(1.0f, 2.0f, 3.0f, 0.1f, 0.2f, 0.3f);
}
double arena_sum = 0;
for (Particle* p : arena_ptrs) arena_sum += p->x;
arena.reset();
end = std::chrono::high_resolution_clock::now();
std::cout << "Arena Allocator: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms (sum=" << arena_sum << ")\n";
// 3. Pool Allocator
PoolAllocator<Particle> pool(count);
std::vector<Particle*> pool_ptrs(count);
start = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < count; ++i) {
pool_ptrs[i] = pool.create(1.0f, 2.0f, 3.0f, 0.1f, 0.2f, 0.3f);
}
double pool_sum = 0;
for (Particle* p : pool_ptrs) pool_sum += p->x;
for (Particle* p : pool_ptrs) pool.destroy(p);
end = std::chrono::high_resolution_clock::now();
std::cout << "Pool Allocator: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
<< " ms (sum=" << pool_sum << ")\n";
return 0;
}
Step 2: Compiling, Sanitizing, and Checking Cache Performance
Start by running with AddressSanitizer and UndefinedBehaviorSanitizer. Pointer math is easy to get wrong, and sanitizers catch alignment or out-of-bounds bugs immediately:
g++ -std=c++20 -O1 -g -fsanitize=address,undefined main.cpp -o benchmark_sanitized
./benchmark_sanitized
Once the sanitized binary passes cleanly, build with -O3 and inspect hardware cache counters under perf stat:
g++ -std=c++20 -O3 main.cpp -o benchmark
perf stat -e cache-misses,cache-references,L1-dcache-load-misses ./benchmark
On a typical Linux desktop, the Arena and Pool runs finish 3x to 10x faster than standard new and delete, with a sharp drop in L1-dcache-load-misses. Profile your flame graphs first. Whenever small, frequent heap allocations show up hot, swap in an Arena or a Pool.

