Projects / Memory allocator / Phase 3
Phase 3 of 4 · about 2.5 hours
Fast for one job
You end with a pool allocator for same-sized objects that works with standard containers, and a benchmark that shows where each allocator wins.
Step 3.1: Why our heap is slow (about 35 minutes)
Look at allocate again: it starts at the first block every time. When the heap holds 20,000 used blocks, finding a free one means walking past all of them. The cost of each call grows with the number of live blocks, so allocating n objects takes time proportional to n squared. malloc implementations avoid this by keeping free lists, lists of free blocks only, usually grouped by size. We will measure our heap in Step 3.4 and the number will be rude. First, build something that has the free-list idea in its simplest form.
Step 3.2: A pool for one size (about 55 minutes)
Many programs allocate millions of objects of the same size: tree nodes, list nodes, particles, requests. For that job we can do much better. A pool keeps one chunk of memory cut into equal slots and a list of the free slots. The trick is that a free slot stores the link to the next free slot inside itself, so the list costs no extra memory. Allocating is "pop the first slot". Freeing is "push this slot". Both are a few instructions. Create pool.hpp:
class Pool {
public:
Pool(std::size_t slot_size, std::size_t slots_per_chunk = 4096)
: slot_size_(round_up(slot_size < sizeof(Slot) ? sizeof(Slot) : slot_size)), per_chunk_(slots_per_chunk) {}
Pool(const Pool&) = delete;
Pool& operator=(const Pool&) = delete;
~Pool() {
for (void* chunk : chunks_) ::operator delete(chunk, std::align_val_t{16});
}
void* allocate() {
if (free_ == nullptr) grow();
Slot* s = free_;
free_ = s->next;
live_++;
return s;
}
void deallocate(void* p) {
Slot* s = static_cast<Slot*>(p);
s->next = free_; // a free slot stores the link inside itself
free_ = s;
live_--;
}
std::size_t slot_size() const { return slot_size_; }
std::size_t live() const { return live_; }
std::size_t chunks() const { return chunks_.size(); }
private:
struct Slot {
Slot* next;
};
static std::size_t round_up(std::size_t n) { return (n + 15) & ~std::size_t{15}; }
void grow() {
auto* chunk = static_cast<std::byte*>(::operator new(slot_size_ * per_chunk_, std::align_val_t{16}));
chunks_.push_back(chunk);
for (std::size_t i = per_chunk_; i-- > 0;) { // thread the new slots onto the free list
auto* s = reinterpret_cast<Slot*>(chunk + i * slot_size_);
s->next = free_;
free_ = s;
}
}
std::size_t slot_size_;
std::size_t per_chunk_;
Slot* free_ = nullptr;
std::size_t live_ = 0;
std::vector<void*> chunks_;
};
Points to notice:
- A slot is at least as big as a pointer, because a free slot holds one.
growallocates a new chunk when the free list is empty and threads its slots onto the list. Chunks are never given back until the pool is destroyed.allocateanddeallocatedo not look at sizes at all. The caller promises every object is the pool's slot size.- The pool does not call constructors. Combine it with placement new, as in Phase 1.
Step 3.3: Plug it into std::list (about 30 minutes)
C++ containers accept an allocator: an object that provides allocate and deallocate. A std::list<int> allocates one node per element, which is exactly the one-size workload a pool is good at. Add the adapter at the bottom of pool.hpp:
// Lets std::list, std::map and friends take their nodes from a Pool.
template <typename T>
class PoolAllocator {
public:
using value_type = T;
explicit PoolAllocator(Pool& pool) : pool_(&pool) {}
template <typename U>
PoolAllocator(const PoolAllocator<U>& other) : pool_(other.pool_) {}
T* allocate(std::size_t n) {
if (n == 1 && sizeof(T) <= pool_->slot_size()) return static_cast<T*>(pool_->allocate());
return static_cast<T*>(::operator new(n * sizeof(T))); // anything else goes to the normal heap
}
void deallocate(T* p, std::size_t n) {
if (n == 1 && sizeof(T) <= pool_->slot_size()) pool_->deallocate(p);
else ::operator delete(p);
}
template <typename U>
bool operator==(const PoolAllocator<U>& o) const { return pool_ == o.pool_; }
private:
template <typename U>
friend class PoolAllocator;
Pool* pool_;
};
The adapter holds a pointer to the pool. It uses the pool for single-object requests that fit in a slot and falls back to the ordinary heap for anything else (a list never asks for more, but a std::vector would). The converting constructor lets the container build an allocator for its own node type. Create try_pool.cpp:
#include <cstdio>
#include <list>
#include "pool.hpp"
int main() {
Pool pool(48);
void* a = pool.allocate();
void* b = pool.allocate();
std::printf("slot size %zu, live %zu, chunks %zu\n", pool.slot_size(), pool.live(), pool.chunks());
pool.deallocate(a);
void* c = pool.allocate();
std::printf("freed slot is reused first: %s\n", c == a ? "yes" : "no");
pool.deallocate(b);
pool.deallocate(c);
std::printf("live after freeing all: %zu\n", pool.live());
// A std::list whose nodes live in the pool. Its node is bigger than an int: the pool sizes itself for it.
Pool node_pool(sizeof(void*) * 2 + sizeof(int));
std::list<int, PoolAllocator<int>> numbers{PoolAllocator<int>(node_pool)};
for (int i = 0; i < 10; i++) numbers.push_back(i);
std::printf("list of %zu numbers, pool live slots: %zu\n", numbers.size(), node_pool.live());
numbers.clear();
std::printf("after clear, pool live slots: %zu\n", node_pool.live());
}
slot size 48, live 2, chunks 1
freed slot is reused first: yes
live after freeing all: 0
list of 10 numbers, pool live slots: 10
after clear, pool live slots: 0
The freed slot was handed out again first (the last-in, first-out behaviour of the free list, which also keeps it hot in the CPU cache). The list's ten nodes lived in the pool, and clear returned them.
Step 3.4: Measure everything (about 30 minutes)
Now the comparison. bench.cpp allocates 20,000 items of 40 bytes, frees them in shuffled order and repeats five times, with operator new, then our heap, then our pool. Then it builds a std::list of two million ints with the standard allocator and with the pool:
#include <chrono>
#include <cstdio>
#include <list>
#include <map>
#include <random>
#include <vector>
#include "heap.hpp"
#include "pool.hpp"
template <typename F>
double seconds(F&& run) {
const auto start = std::chrono::steady_clock::now();
run();
return std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
}
struct Item {
long a, b, c, d, e; // 40 bytes
};
alignas(16) static std::byte heap_buffer[4 << 20];
int main() {
constexpr int kItems = 20'000;
constexpr int kRounds = 5;
long sink = 0;
// Job: allocate 20,000 items, free them in a shuffled order, five times over.
std::vector<int> order(kItems);
for (int i = 0; i < kItems; i++) order[i] = i;
std::shuffle(order.begin(), order.end(), std::mt19937(1));
std::vector<void*> ptrs(kItems);
const double t_malloc = seconds([&] {
for (int r = 0; r < kRounds; r++) {
for (int i = 0; i < kItems; i++) ptrs[i] = ::operator new(sizeof(Item));
for (int i : order) ::operator delete(ptrs[i]);
}
});
Heap heap(heap_buffer, sizeof heap_buffer);
const double t_heap = seconds([&] {
for (int r = 0; r < kRounds; r++) {
for (int i = 0; i < kItems; i++) ptrs[i] = heap.allocate(sizeof(Item));
for (int i : order) heap.deallocate(ptrs[i]);
}
});
Pool pool(sizeof(Item));
const double t_pool = seconds([&] {
for (int r = 0; r < kRounds; r++) {
for (int i = 0; i < kItems; i++) ptrs[i] = pool.allocate();
for (int i : order) pool.deallocate(ptrs[i]);
}
});
std::printf("%d x (allocate %d items, free them shuffled)\n", kRounds, kItems);
std::printf(" operator new %.3f s\n", t_malloc);
std::printf(" our Heap %.3f s\n", t_heap);
std::printf(" our Pool %.3f s (%.1fx faster than operator new)\n", t_pool, t_malloc / t_pool);
// The same pool under a standard container.
const double t_list_std = seconds([&] {
std::list<int> l;
for (int i = 0; i < 2'000'000; i++) l.push_back(i);
for (int v : l) sink += v;
});
Pool node_pool(sizeof(void*) * 2 + sizeof(int));
const double t_list_pool = seconds([&] {
std::list<int, PoolAllocator<int>> l{PoolAllocator<int>(node_pool)};
for (int i = 0; i < 2'000'000; i++) l.push_back(i);
for (int v : l) sink += v;
});
std::printf("std::list of 2,000,000 ints: std::allocator %.3f s, PoolAllocator %.3f s\n", t_list_std, t_list_pool);
return sink < 0;
}
5 x (allocate 20000 items, free them shuffled)
operator new 0.006 s
our Heap 3.936 s
our Pool 0.002 s (3.6x faster than operator new)
std::list of 2,000,000 ints: std::allocator 0.072 s, PoolAllocator 0.038 s
Three results, each with a lesson:
- Our heap is about a thousand times slower than
operator newhere. That is the quadratic scan from Step 3.1, not a typo. This is why a "simple and correct" allocator is not good enough. - The pool is about as fast as
operator newhere. A modernmallocalready keeps caches of small blocks, which behave a lot like a pool. The pool pulls ahead when objects sit side by side with no per-block bookkeeping, as the list result shows. - The list is about twice as fast with the pool, because nodes sit next to each other in memory and there is no per-node bookkeeping.
Your numbers will differ. What should not differ is the order: heap far behind, pool at least as fast as new.
Phase 3 done
You have three allocators and know where each one wins. Last, make the heap safe to debug with.