Goose-style data stacks for C++20: memory that is freed a whole scope at a time, arrays that grow in place without ever moving, 4-, 2- and 1-byte links between objects, and records of different kinds stored back to back, each at its own size. Header-only.
Status: v0.2, experimental. Tested on Linux (x86-64) with GCC 11 to 13 and Clang 16 and 18, including AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer builds (GCC 13, Clang 18). CI also runs the tests on macOS (ARM64, Apple Clang) and Windows (x86-64, MSVC). The benchmarks are from Linux. The API may change.
topstack brings the memory model of Goose to C++ as a library. Goose is a language whose values live on a few data stacks instead of a general heap: allocation is a pointer bump, a scope frees everything it allocated by moving the top back, and arrays grow in place because only the topmost value on a stack may grow. Goose enforces that rule in its compiler; topstack enforces it at runtime and hands out stacks automatically so you rarely have to think about it.
- Why
- A first example
- The rules
- The pieces
- Building and testing
- Finding where Scopes go: topstack-scopes
- Performance
- How it works
- Limitations
- Roadmap
- Credits and license
Programs that build a lot of linked data and then throw it away at once (parsers,
compilers, interpreters, per-frame game state) spend much of their time in malloc
and free: a call per node to create it, a walk over the whole structure to destroy
it, and a header plus size-class rounding on every node. Arenas fix the allocation
side, but the usual C++ arenas still leave you with:
- growable arrays that move. A
std::vectorcopies its elements when it grows, so pointers into it break. topstack'sGrowBufgrows in place: pointers to its elements stay valid for its whole life, with noreserveand no size known in advance. - 8-byte pointers everywhere. topstack's
Ref<T>is a 4-byte link,Ref16<T>a 2-byte one andLink8<T>a 1-byte one, which shrinks pointer-heavy nodes to a half, a quarter or less. - one size for every element. A
std::vectorofstd::variants pads every element to the largest kind. topstack'sRecordBufstores each record at its own size, like Goose's variable-size enums, from plain structs. - manual plumbing. Which arena does this array go in? When is it freed? topstack
gives each growing array its own stack automatically, and a
Scopefrees everything made inside it, running destructors where needed.
#include <topstack/grow_buf.hpp>
#include <topstack/ref.hpp>
#include <cstdio>
struct Node {
int value;
topstack::OptRef<Node> left, right; // 4-byte links that may be null: the node is 12 bytes
};
Node* build(int depth) {
if (depth == 0) return topstack::make<Node>(1, nullptr, nullptr);
Node* l = build(depth - 1);
Node* r = build(depth - 1);
return topstack::make<Node>(depth, l, r);
}
long sum(const Node* n) {
return n ? n->value + sum(n->left.get()) + sum(n->right.get()) : 0;
}
int main() {
{
topstack::Scope scope; // everything made below is freed at the }
Node* root = build(20); // two million nodes, no malloc
std::printf("%ld\n", sum(root));
topstack::GrowBuf<long> squares; // gets its own stack automatically
long* first = squares.push(0L);
for (long i = 1; i < 1'000'000; ++i) {
squares.push(i * i); // grows in place: nothing moves
}
std::printf("%ld %ld\n", *first, squares[999'999]); // first is still valid
} // one rewind frees all of it
}No stack was created by hand: the calling thread has a default set of stacks, created on first use. You can also create and pass stacks explicitly (see below).
topstack is fast because it doesn't track objects individually. In return, there are a few rules. Breaking one stops the program with a message that says what happened, instead of corrupting memory.
- Only the top of a stack grows. A
GrowBufowns the top of its stack while it grows. If something else is allocated on the same stack afterwards, the buffer is sealed; pushing to it again before that allocation is freed is an error. Buffers that get their stack from aStackSet(the default) each have their own stack, so this only comes up when you put a buffer on aStack&yourself. - Scopes free in order. A
Scopefrees everything allocated on its stack since it was opened. Don't use those objects afterwards, and don't let a buffer that was created outside a scope grow inside it on the same stack (that would free part of the buffer). - Build objects that contain links in place. A link (
Ref,OptRef,Ref16,OptRef16) stores the distance from itself to its target, so it must live near its target, on the same stack. Make such objects withmakeorpush(args...), not as local variables or temporaries:
topstack::make<Node>(1, l, r); // fine: built on the stack
buf.push(1, l, r); // fine
buf.push(Node{1, l, r}); // stops (debug): the temporary is on the native stack- Don't link across stacks or threads. Each thread has its own stacks, and they are released when the thread ends. Don't hand pointers into them to other threads.
| Header | What it gives you |
|---|---|
topstack/stack.hpp |
Stack, Scope, and make / alloc on the thread's default stack |
topstack/stack_set.hpp |
StackSet, default_set(), plain_stack() (included by stack.hpp) |
topstack/grow_buf.hpp |
GrowBuf<T> |
topstack/ref.hpp |
Ref<T>, OptRef<T>, Packed<T> |
topstack/ref16.hpp |
Ref16<T>, OptRef16<T> |
topstack/link8.hpp |
Link8<T>, OptLink8<T> |
topstack/pmr.hpp |
StackResource, for the standard std::pmr containers |
topstack/records.hpp |
RecordBuf<Kinds...>, Text, Array: records of different sizes |
topstack/fail.hpp |
fail, catch_from: return an error from any depth |
A Stack reserves a range of address space (2 GB by default, which is also the
maximum) and commits memory as it is used, so a large reservation costs nothing until
it is touched.
auto [stack, err] = topstack::Stack::create(); // or create(reserve, commit_step)
if (!stack) std::puts(topstack::to_string(err));
int* one = stack->make<int>(42); // constructs in place
double* many = stack->make_array<double>(1000);
void* raw = stack->alloc(256, 64); // bytes, alignment
auto [p, e] = stack->try_make<std::string>("hello"); // try_: returns the error toomakeandallocreturnnullptrif the stack is out of space; thetry_versions return{pointer, error}so you can tell why (OutOfReserveorCommitFailed).- Objects with destructors (like
std::string) get a cleanup note, and their destructors run, newest first, when their scope ends. make_arrayis for types without destructors.free_top(p, bytes)frees an allocation if it is the newest thing on the stack (it ends at the top), and returns whether it did. Memory freed in reverse order of allocation, like temporaries, can be given back early this way.- On Linux, building with
TOPSTACK_PREFAULThas the kernel get new memory ready ahead of the top on another core; see Prefaulting.
{
topstack::Scope scope(*stack); // or Scope scope; for the thread's plain stack
... // allocate freely
} // destructors run, then the top moves backUnderneath, a scope is stack.mark() when it opens and stack.rewind(mark) when it
closes; you can call those yourself. In debug builds, freed memory is overwritten with
0xDD so use-after-free bugs show up quickly.
topstack::GrowBuf<Token> tokens; // on a stack lent by the thread's set
topstack::GrowBuf<Token> mine(*stack); // or on a stack you choose
Token* t = tokens.push(kind, start, length); // constructs in place; nullptr if out of space
tokens.size(); tokens[3]; for (Token& t : tokens) { ... }
topstack::GrowBuf<char> text;
char* p = text.extend(n); // n more elements at once, uninitialized
text.truncate(10); // keep the first 10 elements
text.clear(); // empty it; refills from the same place- Elements never move, so pointers and references to them stay valid until the buffer is destroyed.
- Destroying the buffer destroys its elements and gives its space back.
- A buffer can be moved, for example returned from a function, and keeps growing in its new home. A moved-from buffer may only be destroyed or assigned to.
- A push is a compare and a store; it only leaves that fast path to commit more memory or to resume after being sealed.
extend(n)addsnelements in one step without initializing them (for element types that need no constructor, such as bytes); it is the way to write variable-size records into a byte buffer. It returnsnullptrif out of space.truncate(n)keeps the firstnelements and destroys the rest;clear()destroys them all. Either way the buffer keeps its place, so it can be refilled without giving its stack back.
A StackSet owns up to 64 stacks. Stack 0 is for plain allocations; stacks 1 to 63 are
lent to growing buffers, the lowest free one first, and taken back when the buffer is
destroyed. Freed stacks keep their memory for the next buffer.
Every thread gets its own set the first time it needs one (topstack::default_set()),
and the stack-free forms use it: GrowBuf<T> buf;, topstack::make<T>(...),
topstack::alloc(...), topstack::Scope scope;. You can create your own set too:
topstack::StackSet set(std::size_t(1) << 30, std::size_t(256) << 20); // 1 GB plain, 256 MB buffers
topstack::GrowBuf<int> xs(set);More than 63 buffers growing at once on one set is treated as a bug (most likely
buffers that are never destroyed) and stops the program. If the operating system
refuses to reserve a stack, the buffer has no stack and every push returns nullptr.
StackResource (in topstack/pmr.hpp) is a std::pmr::memory_resource, so the
standard std::pmr containers can keep their memory on a stack:
{
topstack::Scope scope;
topstack::StackResource res; // the thread's plain stack, or res(stack)
std::pmr::vector<int> v(&res);
std::pmr::unordered_map<std::pmr::string, int> counts(&res);
... // allocations are bumps of the top
} // the scope frees it all at onceIt works like std::pmr::monotonic_buffer_resource, but grows in place instead of in
chunks, and frees back to any scope instead of only all at once. Freeing gives memory
back when it is the newest thing on the stack (Stack::free_top); everything else
waits for the scope. Three rules:
- Destroy the containers before the scope that frees their memory ends: declare
them after the
Scope, not before. - A growing vector leaves its old buffers behind until the scope ends, because they
aren't at the top any more:
reserve()up front, or use aGrowBuffor big arrays. - One thread, like the stack it uses. It throws
std::bad_allocwhen the stack runs out, asmemory_resourcerequires. This keeps ordinary C++ layout (8-byte pointers, the containers' own node formats), so it gives topstack's allocation speed, not its smaller layouts. It is the easiest way to move existing code onto a stack, and lets strings and vectors inside topstack nodes live on a stack too.
RecordBuf (in topstack/records.hpp) stores records of several kinds in one buffer,
each at its own size, like Goose's variable-size enums. Each kind is a plain struct; a
Text or Array field holds a run of chars or elements whose length is stored in the
record:
struct Tick {};
struct Move { int32_t id; int16_t dx, dy; };
struct Say { int32_t id; topstack::Text<uint8_t> text; }; // up to 255 chars
struct Quit { int32_t id; uint8_t code = 0; };
topstack::RecordBuf<Tick, Move, Say, Quit> log; // its own stack, grows in place
log.push(Move{7, 1, -1}); // 9 bytes: a tag and the fields
log.push(Say{7, "hello"}); // 11 bytes: 1 + 4 + 1 + 5
Say s = log.push(Say{8, topstack::room(3)}); // room for 3 chars, filled after
s.text[0] = 'h'; s.text[1] = 'e'; s.text[2] = 'y';
log.for_each(topstack::overload{ // one lambda per kind, like a match
[&](const Tick&) { ... },
[&](const Move& m) { ... m.dx ... },
[&](const Say& s) { ... s.text.view() ... },
[&](const Quit& q) { ... },
});- Layout: a one-byte tag (the kind's position in the list), then the fields in
declaration order with no padding between them. A
Text<Len>orArray<T, Len>is its length, stored asLen, then its elements.Movetakes 9 bytes where astd::variantof these four kinds takes 24. - Kinds are plain structs (no constructors or base classes; default values are
fine) of up to 32 fields, each trivially copyable or a
TextorArray. The library finds the fields itself, with the C++20 technique Boost.PFR uses. - Reading:
for_eachhands each handler a copy of the record, whoseTexts point at their chars in the buffer, so they can be kept and changed. A handler missing for a kind is a compile error.edittakes records by reference and writes their fixed fields back. - Growing a record:
log.open(Say{9, ""})starts a record whose lastTextorArraygrows withappenduntilclose()or the end of its block, in place, since it is the top of its stack. - Undo:
auto m = log.mark();and laterlog.truncate(m);drop every record pushed after the mark. - No
log[i]: a record's position depends on the sizes before it.bytes()before a push is the record's offset, andread_at(offset, ...)reads it back; store offsets in records to link them (aRefcan't be a record field, since records are copied). - Checks: a
Textlonger than its length type holds stops the program, in release builds too; using a mark anothertruncatewent past, or reading while a record is open, is caught in debug builds. On Goose's records benchmark (bench/records_topstack_api.cpp), it is as fast as the hand-packed version, with the same 143 MB. Frombench/results/2026-11-28_records_api.txt, GCC / Clang:RecordBuf583 / 595 ms, hand-packed 653 / 579 ms, Goose 567 / 662 ms, Goose's expert C++ 1293 / 1207 ms (386 MB).
fail (in topstack/fail.hpp) sends an error straight back to a caller any number of
calls up, like Goose's return ... from. The functions in between keep plain
signatures and check nothing:
int parse_age(std::string_view s) {
int v = 0;
auto [end, ec] = std::from_chars(s.data(), s.data() + s.size(), v);
if (ec != std::errc{} || end != s.data() + s.size()) topstack::fail("bad age");
return v;
}
int load(std::string_view s) { return parse_age(s) + 1; } // nothing about errors
auto r = topstack::catch_from<const char*>(load, "forty"); // or a lambda
if (r.failed) ... r.error ... // "bad age"
else ... r.value ...- Which
catch_from:fail(e)goes to the innermost runningcatch_fromofe's type and skips the others, so catches of different error types can be nested. With none, the program stops. - The error must be trivially copyable: a code, an enum, a struct of numbers, a
string literal. On failure,
valueis default-constructed. - Memory: on the way, the Scopes and GrowBufs in the functions
failleaves are ended as their destructors would end them (stacks rewound, elements destroyed, buffers' stacks given back), andcatch_fromrewinds the plain stack to where it was, freeing everything made since it began. - The rule: those functions can't have other local objects with destructors (a
std::string, astd::vector, aunique_ptr, a lock), sincefailjumps over them withlongjmpinstead of unwinding like an exception. Objects made on a stack withmake()are fine. - Cost: one
setjmppercatch_fromand nothing per call while nothing fails. The bookkeeping makes each Scope and GrowBuf 32 bytes larger;-DTOPSTACK_NO_FAIL, for the whole program, removes it along withfail.hpp. - Against Goose: Goose names the function to return from (
from load) where topstack picks thecatch_fromby error type, and its compiler checks a flag after each call on the way instead of jumping, so it needs no bookkeeping in objects. On Goose's calc benchmark (bench/calc_topstack_fail.cpp), where a quarter of the inputs fail, it is as fast as the same parser returning error codes through every level. Frombench/results/2026-11-29_calc_fail.txt, GCC / Clang:fail726 / 684 ms, error codes 726 / 679 ms, Goose 664 / 682 ms, Goose's expert C++ (arena and error codes) 721 / 695 ms, all 8.3 MB.
struct Expr { std::uint8_t tag; };
struct Bin : Expr { topstack::Ref<Expr> l, r; }; // 9 bytes
struct Num : Expr { topstack::Packed<std::int32_t> v; }; // 5 bytes
Bin* b = topstack::make<Bin>(Expr{1}, left, right);
Expr* l = b->l.get(); // also b->l->..., *b->l, b->l == p- A
Ref<T>is 4 bytes: the signed distance from the link to its target, as in Goose's self-relative references. Following it is one addition. Ref<T>is never null,OptRef<T>may be, like Goose'sT&andT&?. UseOptRefwhere a link can be missing (a leaf's children, the end of a list) andRefeverywhere else: it skips the null check on every read and write, which makes link-heavy code faster (an LRU cache 7%, the interp benchmark 11% with GCC).link = nullptrandif (link)only compile for anOptRef; in debug builds, reading aRefbefore it was set, or setting it to null through a pointer, stops the program.- The target must be within 2 GB of the link, which is always true within one stack.
- Copying a link (or a struct containing one) recomputes the offset for the new place;
copying raw bytes with
memcpydoes not. - Links and
Packed<T>have alignment 1, so a node made of a tag, links andPackedfields has no padding, and such nodes sit back to back on the stack. - Checks: storing a target that is too far away (or at the link's own address) is
checked in debug builds, like
assert. DefineTOPSTACK_CHECKED_REFSto keep the checks in release builds too. On the benchmarks they cost 0 to 10% (tree, with GCC), and 24% on bintrees with Clang, where storing links is almost all the work.
struct Bin : Expr { topstack::Ref16<Expr> l, r; }; // 5 bytes instead of 9Ref16<T> is used exactly like Ref<T>, in half the space, and OptRef16<T> like
OptRef<T>:
- A target within 16 KB of the link is stored directly in the 2 bytes.
- A farther target gets a relay: a 4-byte slot that holds the real offset. Each 64 KB
region of a stack has its own relay table, found from the link's own address, so a
Ref16needs no extra arguments. Relays are freed together with the data they belong to, including by aScope. - In structures built bottom-up, like trees whose children are made before their parent, almost every link is near; the benchmark trees end up with a few hundred relays among millions of links.
struct Tree { topstack::Packed<std::int32_t> v; topstack::OptLink8<Tree> left, right; }; // 6 bytes
Tree* t = topstack::make<Tree>(7, l, r);
t->left->v; // read like a Ref- A target within 64 bytes of the link is stored directly in its one byte.
- A farther target gets an anchor: a 4-byte
Refto the target, made on the stack right after the node, and the link's byte points at the anchor. AScopefrees anchors together with their nodes. - An anchor can only be put right after a node while that node is the newest thing on
its stack, so a
Link8gets its target when its node is made, and never changes after that: it can't be assigned or copied. The node it points to can still be changed. Make such nodes withmake, keep them small (an anchor has to be within 63 bytes of its link), and don't put far links inGrowBufelements; each of these is checked, and breaking it stops the program with a message. Link8<T>is never null,OptLink8<T>may be, as withRefandOptRef. Use it for data that is built once, bottom-up, and then read: trees, parsed expressions, syntax trees. Children made just before their parent are almost always within 64 bytes, so nearly every link takes one byte.
Smaller links take a few more instructions to store and follow. When the data fits in the CPU's cache, that shows and wider links are faster; when it doesn't, smaller nodes mean fewer cache misses and can be faster too. Measured on this machine (faster compiler of the two):
| Benchmark | Data | Ref (4 bytes) |
Ref16 (2 bytes) |
Link8 (1 byte) |
|---|---|---|---|---|
| bintrees | trees of at most a few MB, rebuilt millions of times | 370 ms, 17.9 MB | 404 ms, 9.9 MB | 462 ms, 8.3 MB |
| tree | one tree of 33 million nodes | 1120 ms, 386 MB | 872 ms, 259 MB | 1110 ms, 202 MB |
| interp | one expression tree, about 22 MB | 101 ms, 21.6 MB | 96 ms, 15.8 MB | 90 ms, 13.2 MB |
| sexp | a parsed text, about 380 MB, much of it the text | 1677 ms, 379 MB | 1725 ms, 323 MB | (not ported) |
So: Ref for small, hot data or data that changes; Ref16 for big structures;
Link8 for the least memory on data that is built once, where it is also the fastest
on interp. On tree, Link8 uses 22% less memory than Ref16 but is 27% slower here
(on another machine it was faster), so measure on yours.
topstack is header-only: add include/ to your include path. It needs C++20.
./test.shbuilds each test twice, once normally and once with AddressSanitizer and
UndefinedBehaviorSanitizer, builds three of them again with TOPSTACK_NO_FAIL and,
where liburing is installed, four with TOPSTACK_PREFAULT (normally and with the
sanitizers), then builds two small programs that check plain-stack-only use and a
GrowBuf in a global variable, and runs them all, stopping at the first failure:
tests/stack_test.cpp Stack, alloc, marks, Scope, make, cleanups
tests/grow_buf_test.cpp GrowBuf: growth, sealing, ownership, moving, truncate
tests/stack_set_test.cpp StackSet, default stacks, threads, plain allocations
tests/ref_test.cpp Ref and Packed
tests/ref16_test.cpp Ref16: near and far links, relays across scopes, slot reuse
tests/link8_test.cpp Link8: near links, anchors, freeing, the rules
tests/pmr_test.cpp StackResource with the standard pmr containers
tests/records_test.cpp RecordBuf: layout, Text and Array, open, edit, mark and truncate
tests/fail_test.cpp fail and catch_from: depths, freeing, nesting, the rules
tests/prefault_test.cpp TOPSTACK_PREFAULT: contents while the kernel populates ahead
tests/color_test.cpp stack coloring: offsets, and Ref16 relays at a stack's far end
tests/plain_only.cpp Scope() and make() with only stack.hpp included
tests/global_buf.cpp a GrowBuf in a global variable exits cleanly
The tests that check that rule violations stop the program use fork, so they are
POSIX-only. GitHub Actions runs ./test.sh on every push. With CMake,
-DTOPSTACK_PREFAULT=ON turns on prefaulting for everything that links
topstack::topstack.
A Scope frees everything made since it opened, so it's safe in a function only when
nothing the function makes, or anything it calls makes, is still used after it returns.
tools/topstack-scopes checks that across a whole project and writes the Scopes in.
Your code doesn't change apart from the lines it adds.
It's a Clang tool, built on its own (Ubuntu: apt install llvm-18-dev libclang-18-dev):
cmake -S tools/topstack-scopes -B tools/topstack-scopes/build
cmake --build tools/topstack-scopes/build
tools/topstack-scopes/tests/check.shIt reads your project from compile_commands.json (CMake writes one with
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON):
topstack-scopes -p build --project # where Scopes can go
topstack-scopes -p build --project --explain # and why each other function gets none
topstack-scopes -p build --project --fix # write them intree.cpp:14: warning: nothing 'tree_local' allocates outlives it; add `topstack::Scope scope;`
use.cpp:5: warning: nothing 'use_add' allocates outlives it; add `topstack::Scope scope;`
loops.cpp:15: warning: nothing one iteration of this loop in 'many_trees' allocates outlives the iteration; add `topstack::Scope scope;`
A Scope goes at the start of a function body, or of a loop body when each iteration's
memory is done with by the end of the iteration. It names the stack the memory is on:
Scope scope; for the plain stack, Scope scope(s); for a Stack& parameter or a
global. With --project, naming files reports on just those (and the project's headers
they include) while still reading the whole project. Files named without --project
are read alone: calls into other files count as unknown code, and templates from
headers get no Scope, since other files may use them with other types. --low-memory
keeps one file parsed at a time: slower, same answers.
To see suggestions while building, set it as CMake's clang-tidy:
set(CMAKE_CXX_CLANG_TIDY /path/to/topstack-scopes). Each file is then read alone, as
above, so it suggests fewer; --project is the full answer.
How it decides: for every function it works out which stacks it leaves memory on, and
whether that memory can leave it — returned, stored through a parameter or this, kept
in a global, passed to code it can't see. Callers get the callee's answers, round after
round across the project, until nothing changes. It follows lambdas (and what they
capture by reference), virtual calls (any override in the project), calls through
function pointers (any function of that type whose address is taken), destructors,
templates (a Scope only where every instance agrees), and indices: a number made from a
pointer difference counts as a pointer, as do numbers read from wherever such numbers
are stored.
It assumes no undefined behavior, that C library functions don't use topstack, that
function pointers and virtual calls only reach code in the project, and one thread per
stack. It doesn't yet look at if blocks or other plain blocks, or at stacks it can't
name at the start of the function (a local unique_ptr<Stack>), and code outside
compile_commands.json is unknown, so a function calling it gets no Scope. The Scope
is named scope; a function that already has a scope needs it renamed.
All numbers are from one machine and one run: WSL2 (Linux 6.6) on a 16-core AMD Ryzen 9
6900HX, GCC 13.3 and Clang 18.1, -O2 (bench/results/2026-11-30_1813.txt; the
bumpalo and protobuf rows from 2026-11-30_2037.txt, run right after). Each program ran
7 times; the first 2 runs are warm-ups and the tables show the fastest of the rest.
Memory is peak resident memory. Every program printed exactly what Goose's own version
prints.
The benchmarks are all 16 of Goose's own
(bench/ in the Goose repository), at the largest sizes Goose's runner uses. To keep
the comparison fair:
- Every side is built with both GCC and Clang, Goose included, and the faster build counts. (Which compiler wins varies a lot: Goose's blur runs 5x faster with Clang, its bintrees 20% faster with GCC.)
- Every version each side has counts. For Goose that includes its alternative
versions (a CSR graph, a streaming respond, a dictionary for words) and, for the
four tree benchmarks, Goose's programs rebuilt with its smallest links
(
&<varint>, 1 byte for a near target), which match topstack'sLink8in memory. For topstack it includes all link widths. For C++, Goose's "expert" versions; for Rust, all of Goose's Rust versions. - Speed compares each side's fastest version; memory each side's smallest.
- Huge pages are off for everyone, topstack included (it asks for them by default;
the benchmark scripts build it with
TOPSTACK_NO_HUGE_PAGES). What they add is in Huge pages below.
How many times faster topstack is / how many times less memory it uses. Above 1.00x, topstack wins.
| Benchmark | vs Goose | vs expert C++ | vs Rust |
|---|---|---|---|
| bintrees | 0.71x / 1.00x | 1.11x / 4.04x | 1.23x / 3.12x |
| push | 0.97x / 1.00x | 1.02x / 1.00x | 1.05x / 1.00x |
| tree | 1.38x / 0.97x | 1.41x / 1.91x | 1.60x / 1.91x |
| interp | 1.14x / 0.98x | 2.01x / 3.74x | 2.22x / 2.82x |
| sexp | 1.08x / 0.89x | 1.77x / 2.96x | 1.36x / 2.05x |
| sum | 0.94x / 1.00x | 0.93x / 1.00x | 0.96x / 1.00x |
| strlist | 1.03x / 1.12x | 1.22x / 1.00x | 1.13x / 1.14x |
| records | 0.98x / 1.00x | 2.11x / 2.70x | 2.38x / 4.29x |
| graph | 0.21x / 1.00x | 0.25x / 1.00x | 0.28x / 1.00x |
| words | 0.92x / 0.92x | 1.46x / 1.11x | 1.44x / 1.22x |
| particles | 0.96x / 1.00x | 0.78x / 1.00x | 0.98x / 1.00x |
| lru | 0.95x / 1.00x | 1.00x / 1.02x | 1.01x / 1.00x |
| scene | 1.00x / 0.98x | 1.27x / 1.32x | 0.98x / 1.00x |
| calc | 0.96x / 1.00x | 1.01x / 1.00x | 0.90x / 1.00x |
| respond | 0.80x / 1.00x | 1.01x / 1.00x | 1.20x / 1.00x |
| blur | 0.81x / 1.00x | 1.01x / 1.00x | 0.87x / 1.00x |
| geometric mean | 0.88x / 0.99x | 1.11x / 1.44x | 1.12x / 1.40x |
What it shows:
- Against Goose, Goose is ahead overall when each side brings its best: topstack
runs at 0.88x Goose's speed with the same memory. Most of the gap is in three places:
- Designs topstack has no port of: Goose's CSR graph (more than 4x faster than the linked graph that topstack, like Goose's main version, builds), its streaming respond, and its dictionary for words. Comparing only the same data structures, topstack is within 2% of Goose's speed (0.98x) and uses 1% less memory (1.01x).
- bintrees (0.71x): how the allocation compiles inside the recursion, below.
- blur (0.81x): Goose's loop, built with Clang, is faster than the same loop in C++ and Rust too. topstack's version uses the expert C++ loop and now runs even with it (1.01x); it used to be 24% slower, because its two images sat on two stacks whose addresses lined up. See Stack coloring.
- Memory against Goose is even. With its smallest links, Goose matches topstack's
1-byte
Link8(bintrees 8.3 MB each, tree 196 against 202 MB, interp 13.0 against 13.2 MB) and is smaller on sexp (288 against 323 MB). topstack is faster at the same memory on tree (1230 against 1446 ms) and interp (90 against 102 ms). - Against expert C++ and Rust: about 1.1x faster with 1.4x less memory, and up to 2.4x faster (records against Rust) and 4.3x less memory (records against Rust). topstack loses where they use a different design (CSR graph; structure-of-arrays particles), and by a few percent on sum, calc and, against Rust, blur. Comparing only the same data structures (leaving out their CSR and nested-vector graphs, their streaming responds and C++'s structure-of-arrays particles), topstack is 1.24x faster than expert C++ and 1.25x faster than Rust, with the same 1.44x and 1.40x less memory.
- With prefaulting (opt-in, Linux), topstack is 14% faster on these benchmarks for 7% more memory: about 1.02x Goose's speed overall and 1.13x on the same data structures.
- Against other C++ arenas (BDE, Folly, Boost,
std::pmr, LLVM, protobuf, mimalloc's heaps), on tree-shaped data: topstack is 1.1 to 1.7x faster on five of six benchmarks and 6% faster on the sixth (calc), with 1.2 to 3.7x less memory (6x with 1-byte links on bintrees). That comes from links smaller than pointers: as a plain allocator with the same 8-byte pointers, topstack is about even with the best of them, and ahead where small trees are made and thrown away. See Other allocators.
Each cell: time, peak memory, and which version. Bold marks the best in a row.
| Benchmark | Goose | topstack | Expert C++ | Rust |
|---|---|---|---|---|
| bintrees, depth 19 | 281 ms, 25.5 MB; &<varint>: 480 ms, 8.3 MB |
396 ms, 17.9 MB (OptRef); 499 ms, 8.3 MB (OptLink8) |
439 ms, 33.5 MB (vector arena) | 489 ms, 25.9 MB (Vec arena) |
| push, 64M items | 569 ms, 498 MB | 583 ms, 497 MB | 593 ms, 498 MB (vector + exact reserve) | 613 ms, 498 MB (Vec + reserve) |
| tree, depth 24 | 1195 ms, 386 MB; &<varint>: 1446 ms, 196 MB |
869 ms, 259 MB (OptRef16); 1230 ms, 202 MB (OptLink8) |
1222 ms, 386 MB (vector arena) | 1391 ms, 386 MB (Vec arena) |
| interp, depth 24 | 103 ms, 21.8 MB; &<varint>: 102 ms, 13.0 MB |
90 ms, 13.2 MB (Link8) |
181 ms, 49.4 MB (tagged union + arena) | 199 ms, 37.2 MB (Vec arena) |
| sexp, N = 300,000 | 1861 ms, 370 MB; &<varint>: 1782 ms, 288 MB |
1647 ms, 379 MB (OptRef); 1703 ms, 323 MB (OptRef16) |
2916 ms, 955 MB (arena + string_view) | 2237 ms, 663 MB (Vec arena) |
| sum, 128M items | 829 ms, 490 MB | 884 ms, 490 MB | 820 ms, 490 MB (vector + reserve) | 845 ms, 490 MB |
| strlist, 8M words | 507 ms, 216 MB | 492 ms, 192 MB | 599 ms, 193 MB (flat offsets) | 559 ms, 219 MB (Vec<&str>) |
| records, 16M events | 528 ms, 143 MB | 537 ms, 143 MB | 1133 ms, 386 MB (variant + fixed buffer) | 1276 ms, 612 MB (enum + String) |
| graph, 2M vertices | linked: 5162 ms, 155 MB; CSR: 1123 ms, 216 MB | linked: 5336 ms, 154 MB | CSR: 1345 ms, 215 MB; linked: 4819 ms, 154 MB | CSR: 1499 ms, 215 MB |
| words, 16M words | 1925 ms, 529 MB; dictionary: 2111 ms, 417 MB | 2101 ms, 452 MB | 3071 ms, 664 MB (open addressing) | 3016 ms, 668 MB (open addressing) |
| particles, 4M | 1769 ms, 93.5 MB | 1835 ms, 93.0 MB | 1438 ms, 93.4 MB (structure of arrays) | 1794 ms, 93.2 MB |
| lru, 32M operations | 2987 ms, 127 MB | 3132 ms, 127 MB (Ref) |
3135 ms, 130 MB (arena + open addressing) | 3170 ms, 127 MB (open addressing) |
| scene, depth 16 | 710 ms, 180 MB | 710 ms, 184 MB (Ref) |
900 ms, 242 MB (arena + indices) | 694 ms, 184 MB (arena) |
| calc, 1.6M inputs | 636 ms | 662 ms (Ref16) |
671 ms (arena + error codes) | 593 ms (arena + Result) |
| respond, 1.6M requests | DTO: 651 ms; streaming: 511 ms | DTO: 641 ms | streaming: 650 ms | streaming: 766 ms |
| blur, 8192×8192 | 430 ms | 533 ms | 537 ms (row pointers) | 464 ms |
calc and respond use 8.4 MB in every version, blur 130 MB. words' C++ and Rust versions hash with FNV-1a, one byte at a time; Goose and topstack use Goose's own hash, 8 bytes at a time.
Every stack lives in a 16 GB block aligned to 16 GB, which is how a Ref16 finds its
relay tables. Each stack's data used to start exactly at its block's start, so the same
offset in two stacks had the same low 34 address bits. Code that goes through two
stacks side by side then makes them compete for the same cache slots. Most likely this
is because AMD's Zen cores predict an L1 cache way from a hash of address bits 12 to 27,
and with huge pages even the physical addresses line up. blur's two images are two growing buffers
on two stacks, read and written at the same offsets; that is why it was 24% slower than
the same loop in C++.
Now each stack's data starts a different number of pages into its block, 0 to 1 MB, spread so that stacks made one after another land far apart. On this machine blur's 16 passes got 20 to 25% faster, and building its two images 1.4x faster with 4 KB pages and 4x faster with huge pages (the default build); in the tables, blur went from 714 to 533 ms. The other benchmarks don't go through two stacks in lockstep and didn't change beyond run-to-run noise. An Intel Xeon showed no effect either way.
topstack asks the system for huge pages (2 MB instead of 4 KB) for each stack's memory
beyond its first 2 MB, so big data needs far fewer TLB entries, and turns them off for
the first 2 MB, so small stacks stay small. TOPSTACK_NO_HUGE_PAGES turns this off.
Goose turns them off for the first 2 MB too, but never asks for them beyond it, and
glibc's malloc only asks when told to (GLIBC_TUNABLES=glibc.malloc.hugetlb=1).
What a program gets depends on the system setting
(/sys/kernel/mm/transparent_hugepage/enabled). bench/compare_hugepages.sh runs
everything under both (bench/results/2026-11-30_1813.txt); best of GCC and Clang.
madvise (Ubuntu's default): only programs that ask get huge pages, so Goose runs
without them. Huge pages off → on:
| Benchmark | topstack | expert C++ (with the tunable) | Goose |
|---|---|---|---|
| tree | 873 → 721 ms (−17%) | 1227 → 902 ms (−27%) | 1222 ms |
| sexp | 1854 → 1529 ms (−18%) | 3192 → 2001 ms (−37%) | 1944 ms |
| records | 692 → 533 ms (−23%) | 1307 → 887 ms (−32%) | 568 ms |
| graph | 5776 → 5181 ms (−10%) | 5028 → 4569 ms (−9%) | 5310 ms |
| words | 2361 → 1827 ms (−23%) | 3473 → 2421 ms (−30%) | 2126 ms |
| lru | 3280 → 2901 ms (−12%) | 3168 → 2812 ms (−11%) | 3002 ms |
| scene | 744 → 592 ms (−20%) | 978 → 671 ms (−31%) | 718 ms |
always: every program gets huge pages beyond the first 2 MB without asking, Goose
and plain C++ included, so this is like for like:
| Benchmark | topstack | expert C++ | Goose |
|---|---|---|---|
| tree | 728 ms | 883 ms | 895 ms |
| sexp | 1458 ms | 1796 ms | 1648 ms |
| records | 459 ms | 664 ms | 444 ms |
| graph | 4967 ms | 4403 ms | 4761 ms |
| words | 1642 ms | 2122 ms | 1580 ms |
| lru | 2842 ms | 2728 ms | 2649 ms |
| scene | 592 ms | 638 ms | 606 ms |
- topstack's default is 10 to 23% faster on these benchmarks, for 0 to 1.0% more memory (each stack's last huge page is backed in full), with nothing to set.
- Under
madvise, topstack is the fastest on five of the seven; C++ with the tunable wins graph and lru. Part of that lead is that Goose doesn't ask. - With huge pages for everyone (
always), topstack is the fastest on three (tree, sexp, scene), and behind on four: Goose wins records (by 3%), words (4%) and lru (7%), C++ wins graph (13%). Goose gains 10 to 27% from huge pages, C++ 12 to 49% (mallocspreads small objects over more memory, so it misses the TLB more often to begin with). - The main tables keep huge pages off for everyone. (With
defragatmadvise, as here, a program that doesn't ask only gets huge pages when they're free at once; one that asks may wait for the system to make them.)
The first write to each new 4 KB page stops the program while the kernel finds, zeroes
and maps the page. For a program that fills hundreds of MB, that is a large part of its
time, and no allocator can avoid it. With TOPSTACK_PREFAULT (opt-in; Linux 5.14 or
later and liburing), a stack that has grown past 1 MB asks the kernel, through io_uring,
to do this for a window ahead of its top (an eighth of the stack, 1 to 8 MB), so a
kernel worker does it on another core while the program goes on. It only acts where
pages are 4 KB: built with TOPSTACK_NO_HUGE_PAGES, or on a system with transparent huge
pages set to never. With huge pages there are 512 times fewer faults, and it would only
use more memory.
Turn it on for the whole program: -DTOPSTACK_PREFAULT=ON with CMake, which also links
liburing, or -DTOPSTACK_PREFAULT on every file's command line plus -luring (Ubuntu:
apt install liburing-dev). It adds two members to Stack, so it must be the same in
every file. Where io_uring isn't allowed (Docker's default profile, old kernels), the
program runs as without it.
From bench/results/2026-11-30_prefault.txt (bench/compare_prefault.sh), huge pages
off as in the tables above; topstack's fastest version (best of GCC and Clang) and
smallest memory, without and with prefaulting:
| Benchmark | Time | Ratio | Memory |
|---|---|---|---|
| bintrees | 344 → 341 ms | 0.99x | 5.5 → 6.5 MB |
| push | 527 → 272 ms | 0.52x | 497 → 505 MB |
| tree | 818 → 679 ms | 0.83x | 202 → 208 MB |
| interp | 85 → 81 ms | 0.94x | 13.2 → 14.5 MB |
| sexp | 1599 → 1382 ms | 0.86x | 323 → 334 MB |
| sum | 825 → 536 ms | 0.65x | 490 → 496 MB |
| strlist | 483 → 356 ms | 0.74x | 192 → 207 MB |
| records | 527 → 445 ms | 0.84x | 143 → 148 MB |
| graph | 5404 → 5428 ms | 1.00x | 154 → 161 MB |
| words | 1936 → 1738 ms | 0.90x | 452 → 472 MB |
| particles | 1703 → 1714 ms | 1.01x | 93.0 → 100 MB |
| lru | 3137 → 3017 ms | 0.96x | 126 → 139 MB |
| scene | 684 → 615 ms | 0.90x | 184 → 188 MB |
| calc | 630 → 634 ms | 1.01x | 1.6 → 1.8 MB |
| respond | 626 → 631 ms | 1.01x | 1.6 → 1.8 MB |
| blur | 521 → 450 ms | 0.86x | 130 → 143 MB |
| geometric mean | 0.86x | 1.07x |
- 14% faster overall, for 7% more memory. Programs that write a lot of fresh memory gain most: push 1.9x, sum 1.5x, strlist 1.35x, tree, records, sexp and blur 1.16 to 1.2x. Programs that keep reusing the same memory (bintrees, graph, particles, calc, respond) don't change.
- Memory: the window ahead of the top, 1.5 to 10% more; small programs pay the 1 MB minimum (bintrees 5.5 → 6.5 MB).
- Applied to the Summary (two runs combined, so approximate): about 1.02x Goose's speed with 0.92x its memory, 1.13x on the same data structures, 1.28x against expert C++ and 1.30x against Rust.
- It needs a free core: on a machine already busy on every core, the zeroing competes with the program instead of running beside it.
- A stack should be destroyed on the thread that grew it, as topstack's rules already ask; otherwise a request may still be running when its memory is unmapped, which the kernel handles safely but can cost a little memory.
cJSON ported three ways, on the three files of
the nativejson-benchmark (bench/compare_json.sh), against cJSON itself and
RapidJSON 1.1.0:
- Level 1, allocator hooks (
bench/json/cjson.cpp -DHOOKS=1): cJSON's owncJSON.c, unchanged, given a topstack stack throughcJSON_InitHooks.freeonly takes back the newest allocation, and aScopefrees each document withoutcJSON_Delete. - Level 2, topstack layout (
bench/json/topstack.cpp): cJSON's parser and printer, same algorithm and the same output byte for byte, with a 5-byte header per value (OptReflinks), keys and strings inline, no padding. cJSON's node is 64 bytes plus amallocper string. - Level 3,
Link8(bench/json/link8.cpp): level 2 with 1-byte links, built bottom-up; parse-only (the tree can be read and printed, not edited). - Fast (
-DFAST=1): levels 2 and 3 with faster parsing code and the same output:std::from_charsandstd::to_charsfor numbers instead of cJSON'sstrtod,sprintfandsscanf, and 8 bytes at a time when scanning strings and whitespace. This code isn't topstack's; it would speed up cJSON too. Separate rows, so the layout and the code are measured apart. - RapidJSON:
Parse,ParseInsitu, and its default number mode, which is faster but reads 13% of canada's numbers one or two steps off the nearest double (a 64-bit integer times a power of ten, rounded twice). Every other version reads numbers exactly; the script checks that all of them agree. Frombench/results/2026-11-30_1813.txt; best of GCC and Clang; 200, 100 and 10 rounds. Parse and walk, time and peak memory (the peak includes the input text and about 1.2 MB for the program itself):
| twitter (632 KB) | citm_catalog (1.7 MB) | canada (2.3 MB) | |
|---|---|---|---|
| cJSON | 324 ms, 3.9 MB | 358 ms, 6.9 MB | 210 ms, 16.5 MB |
| level 1 (hooks) | 223 ms, 3.5 MB | 256 ms, 6.0 MB | 172 ms, 13.9 MB |
level 2 (OptRef) |
133 ms, 2.6 MB | 167 ms, 3.9 MB | 133 ms, 5.6 MB |
level 3 (Link8) |
152 ms, 2.6 MB | 185 ms, 3.6 MB | 138 ms, 4.9 MB |
| level 2, fast | 89 ms, 3.0 MB | 94 ms, 4.1 MB | 47 ms, 6.0 MB |
| level 3, fast | 101 ms, 3.0 MB | 107 ms, 3.9 MB | 52 ms, 5.4 MB |
RapidJSON Parse |
334 ms, 3.5 MB | 281 ms, 5.8 MB | 114 ms, 8.7 MB |
RapidJSON ParseInsitu |
168 ms, 3.1 MB | 204 ms, 5.8 MB | 107 ms, 8.6 MB |
| RapidJSON, inexact numbers | 174 ms, 3.1 MB | 198 ms, 5.8 MB | 63 ms, 8.7 MB |
The tree itself, the bytes one parsed document uses (the same on any machine, and for the fast builds):
| citm_catalog | canada | ||
|---|---|---|---|
| cJSON | 1.87 MB | 3.88 MB | 13.4 MB |
| level 1 | 1.38 MB | 2.86 MB | 10.7 MB |
| level 2 | 0.48 MB | 0.64 MB | 1.95 MB |
| level 3 | 0.44 MB | 0.47 MB | 1.28 MB |
RapidJSON Parse |
0.76 MB | 1.09 MB | 2.68 MB |
RapidJSON ParseInsitu |
0.44 MB + input | 1.02 MB + input | 2.68 MB + input |
(In situ, the strings stay in the input text, which has to be kept as long as the tree.)
Parse, walk and print:
| citm_catalog | canada | ||
|---|---|---|---|
| cJSON | 640 ms | 595 ms | 915 ms |
| level 1 | 452 ms | 460 ms | 844 ms |
| level 2 | 310 ms | 302 ms | 771 ms |
| level 3 | 335 ms | 320 ms | 790 ms |
| level 2, fast | 212 ms | 161 ms | 200 ms |
| level 3, fast | 234 ms | 184 ms | 209 ms |
| RapidJSON, best exact | 284 ms | 257 ms | 180 ms |
| RapidJSON, inexact numbers | 273 ms | 246 ms | 137 ms |
- Hooks alone make cJSON 1.2 to 1.5x faster, with no change to cJSON: allocation
becomes a bump and freeing a document a single step. The tree also shrinks by 20 to
26% (no
mallocheaders). Printing can use a bit more memory than withmalloc, because cJSON grows its print buffer by copying it and a stack can't take back the old copies. - The topstack layout makes it 1.6 to 2.4x faster and 4 to 7x smaller than cJSON, with the same parsing code: the gain is the memory layout alone. That is already 1.2 to 1.3x faster than RapidJSON's fastest mode on twitter and citm_catalog.
- Faster parsing code makes level 2 another 1.5 to 2.9x faster, 3.6 to 4.5x faster
than cJSON in all. cJSON's own code was its bottleneck: glibc's
strtodon a copy of each number (60% of the instructions on canada), scanning one byte at a time, and printing each number withsprintf, then reading it back withsscanfto check it. - Level 2, fast, parses 1.4 to 2.1x faster than every RapidJSON mode, including its inexact one, with less peak memory (3 to 30% less). With printing it is faster on twitter (1.3x) and citm_catalog (1.5x); RapidJSON prints canada faster, because cJSON's number format, kept here byte for byte, can take three conversions per number.
- Level 3's tree is 42 to 57% smaller than RapidJSON's, and levels 2 and 3 have the lowest peak memory on every file.
Link8saves 8 to 34% overOptRefand costs 3 to 14% of the parse time (11 to 14% with the fast code; building bottom-up looks at each key twice).- The fast builds' peak memory is 0.2 to 0.4 MB higher: the code for
from_charsandto_chars, linked in statically. Their trees are the same size.
The well-known C++ arenas on the same program, each node allocated before its children,
16-byte pointer nodes, and every library used both its usual way and its fastest way
(bench/compare_arenas.sh: Folly v2026.11.23.00, BDE 4.39.0.0, Boost 1.83, mimalloc
2.1.2). From bench/results/2026-11-28_arenas.txt, best of GCC and Clang:
| Time | Memory | |
|---|---|---|
topstack StackResource (std::pmr) |
362 ms | 33.6 MB |
topstack, OptRef |
387 ms | 17.9 MB |
topstack, OptRef16 |
424 ms | 9.9 MB |
| C++ vector arena with 32-bit indices (Goose's "expert" C++) | 431 ms | 33.6 MB |
| topstack, 8-byte pointers | 433 ms | 33.9 MB |
std::pmr::monotonic_buffer_resource, one reused buffer |
439 ms | 49.8 MB |
Bloomberg BDE SequentialPool, rewound per tree |
451 ms | 49.6 MB |
BDE SequentialAllocator, rewound / one per tree |
455 / 488 ms | 49.6 / 33.4 MB |
Folly SysArena, cleared per tree |
460 ms | 50.2 MB |
std::pmr::monotonic_buffer_resource, one per tree |
470 ms | 33.5 MB |
topstack, OptLink8 |
480 ms | 5.5 MB |
BDE BufferedSequentialAllocator, one reused buffer |
593 ms | 49.6 MB |
Boost pmr::monotonic_buffer_resource, reused buffer / one per tree |
648 / 689 ms | 49.5 / 33.2 MB |
Folly SysArena, one per tree |
1045 ms | 33.6 MB |
mimalloc heap per tree (mi_heap_destroy) |
1046 ms | 33.6 MB |
The rest, from the first bintrees section of bench/results/2026-11-30_1813.txt
(Goose 281 ms; topstack OptRef 396 ms and the vector arena 439 ms in that run):
| Time | Memory | |
|---|---|---|
Rust Vec arena |
489 ms | 25.9 MB |
LLVM BumpPtrAllocator |
925 to 1085 ms | 33.8 MB |
| C++ new/delete | 2496 ms | 65.5 MB |
Rust Box |
3039 ms | 65.9 MB |
Per-node allocation with faster mallocs, from the malloc section of
bench/results/2026-11-30_1813.txt (Goose: 269 ms):
| Time | Memory | |
|---|---|---|
| C++ new/delete with mimalloc / tcmalloc / jemalloc / glibc | 1312 / 1673 / 2110 / 2340 ms | 34 / 41 / 42 / 66 MB |
Rust Box with mimalloc |
1572 ms | 34.2 MB |
LLVM BumpPtrAllocator with tcmalloc / mimalloc |
451 / 475 ms | 40.5 / 42.1 MB |
- topstack's
OptRefis 1.11x faster than the fastest other arena (the vector arena) with half its memory, andOptLink8uses 6 to 9x less memory than any of them. This comes from 4-, 2- and 1-byte links, which only work because a stack's memory never moves. - As a plain allocator,
StackResourceis the fastest here. Through the samestd::pmrcalls as the standard library's arena, in the same allocation order as the BDE, Folly and Boost programs, it is 1.21x faster thanmonotonic_buffer_resourcewith a reused buffer, 1.25x faster than BDE's pool and 1.27x faster than Folly's arena. That order (each node before its children) lays the tree out in the order the check walks it; the other topstack programs make children first, as Goose does. The lead depends on the CPU: on a 2-core Intel Xeon,StackResourcewas 17% slower thanmonotonic_buffer_resourcewhile running 25% fewer instructions. - Folly's
SysArenagets 4 KB blocks frommalloc: a new one per tree frees them all each time, a cleared one keeps them. Boost'smonotonic_buffer_resourceis 1.5x slower than the standard library's on the same program. mimalloc's heaps are not bump allocators: they still sort allocations into size classes. - LLVM's allocator gets and frees its chunks through
malloc; with glibc'smallocon this machine that halves its speed, with tcmalloc it is on par with the others. - A better
mallocmakes per-node allocation up to 1.8x faster, but it stays more than 3x slower than an arena: freeing a tree node by node is the cost, not finding memory. - Rust's
bumpalo, frombench/results/2026-11-30_2037.txt: bintrees 435 ms / 33.8 MB, tree 2214 ms / 770 MB, interp 263 ms / 73 MB, sexp 2089 ms / 838 MB. Its 8-byte references and doubling chunks cost both time and memory. - Google's protobuf
Arena, from the same file (Goose 263 ms, topstackOptRef367 ms): 617 ms and 50 MB with one arena reused for every tree, and 1916 to 2063 ms (34 MB) with a new arena or aReset()per tree, about as slow as plain new/delete. (bench/compare_protobuf.shruns it; it needslibprotobuf-dev.)
tree, interp, sexp, calc and scene on BDE's SequentialPool and
std::pmr::monotonic_buffer_resource, the fastest other arenas above. Each benchmark
is one program (bench/*_arena.cpp) built once per arena with 8-byte pointers, so the
allocator is the only difference (bench/arena.h): Goose's idiomatic C++ version with
new replaced by the arena. Next to them, topstack's own version from the main tables.
From bench/results/2026-11-28_arenas_more.txt (bench/compare_arenas_more.sh), and
for tree and interp from bench/results/2026-11-28_arenas_more_tree_interp.txt, a rerun
with topstack's fastest versions of those two added; best of GCC and Clang:
| topstack, 8-byte pointers | BDE SequentialPool |
std::pmr |
topstack's own version | |
|---|---|---|---|---|
| tree | 1216 ms, 770 MB | 1104 ms, 770 MB | 1077 ms, 770 MB | 920 ms, 259 MB (OptRef16) |
| interp | 162 ms, 48.8 MB | 175 ms, 50.0 MB | 169 ms, 49.4 MB | 100 ms, 13.2 MB (Link8) |
| sexp | 2888 ms, 635 MB | 2863 ms, 664 MB | 2801 ms, 635 MB | 1741 ms, 379 MB (OptRef) |
| calc | 653 ms | 690 ms | 693 ms (reused buffer), 749 ms | 685 ms (Ref16) |
| scene | 961 ms, 220 MB | 954 ms, 220 MB | 957 ms, 221 MB | 741 ms, 184 MB (Ref, one array) |
- As a plain allocator, topstack is about even with both. On sexp and scene the
three are within 3% of each other. On tree they swapped places between the two runs:
topstack with pointers was the fastest in the first (1096 ms against BDE's 1104 and
std::pmr's 1125) and 13% behindstd::pmrin the rerun, so the difference there is within how much a 770 MB benchmark varies from run to run. It is ahead on interp (4 to 14% over the two runs) and calc (6 to 15%), where small trees are made and thrown away for every input. - topstack's own versions are 1.17 to 1.70x faster than either arena on tree, interp, sexp and scene, with 1.2 to 3.7x less memory: 2-byte links on tree, 1-byte links on interp.
- calc's trees are small enough to stay in the CPU's cache, so smaller links don't help there: topstack's own version, with 2-byte links, is 5% slower than with pointers.
On bintrees, the remaining gap is how the allocation compiles inside the recursion,
not the allocator's design. Goose's allocation is a plain bump: each stack has a guard
region after it and the kernel backs pages as they are first touched, so there is no
limit check, and Goose passes the stack's top into each function and returns it, so it
stays in a CPU register for the whole recursion. topstack's alloc keeps the top in
memory and checks the limit, so a full stack returns null instead of crashing.
Written Goose's way by hand (bench/bintrees_thread.cpp: the top passed through calls,
no check), the same benchmark runs in 216 ms with GCC, 23% faster than Goose (281 ms
in the same run). With Clang it takes 396 ms, because Clang doesn't inline the recursive
calls. Removing only the check from topstack, as an experiment, gained 0 to 9% with GCC
and up to 22% with Clang, so the check is only part of the gap; the rest is still under
investigation. Getting this automatically needs compiler support; see the roadmap.
From bench/, with Goose built at ~/programming/goose/build/goose (or set GOOSE=):
./report.shruns everything (about an hour and a half) and saves the output in bench/results/;
./report.sh hugepages json runs just those two scripts, and so on. The individual
scripts are compare.sh (bintrees, push, std::pmr, Goose's C++ and Rust),
compare_extra.sh (LLVM's allocator and pinned_vector), compare_malloc.sh
(mimalloc, jemalloc, tcmalloc), compare_more.sh (tree, interp, sexp),
compare_bumpalo.sh (Rust's bumpalo), compare_suite.sh (the other 11 benchmarks;
./compare_suite.sh records runs one), compare_protobuf.sh (protobuf's Arena),
compare_hugepages.sh (huge pages on and off, under both system settings; it asks for
sudo to switch the setting and puts it back) and compare_json.sh (cJSON and RapidJSON;
it downloads cJSON and its three JSON files). Two more run on their own, not from
report.sh: compare_arenas.sh (Folly, BDE, Boost and mimalloc on bintrees; it
downloads and builds Folly and BDE, and needs the packages listed at its top),
compare_arenas_more.sh (tree, interp, sexp, calc and scene on BDE and std::pmr) and
compare_prefault.sh (TOPSTACK_PREFAULT off and on; it needs liburing).
Requirements beyond GCC and Clang:
sudo apt install llvm-18-dev libmimalloc2.0 libjemalloc2 libtcmalloc-minimal4t64 libprotobuf-dev rapidjson-dev liburing-dev
git clone https://github.com/mknejp/vmcontainer.git ~/programming/vmcontainer
curl --proto '=https' -sSf https://sh.rustup.rs | sh # for the Rust rowsC++ programs are linked with -static-libstdc++ so that loading the C++ standard
library (about 2.4 MB) doesn't count against them; Goose and Rust programs don't pay
it either. Each section of a run measures Goose again, and the machine's speed drifts
by up to 10% over a run, so compare rows within one section. Every script builds Goose
and the C++ versions with both GCC and Clang, and Goose's tree benchmarks also with
&<varint> links (*_goose_varint).
- Every stack is a 16 GB block of address space aligned to 16 GB: up to 2 GB of
data near the start, and room for
Ref16relay tables after it. Because of the alignment, any address inside a stack finds its block's start by masking off the low bits. Only address space is reserved; nothing uses memory until it is written. - Stack coloring: each stack's data starts 0 to 1 MB into its block, a different number of pages for each stack, so two stacks used side by side don't compete for the same cache slots. The relay tables cover that extra 1 MB.
- Committing happens in steps that start at 64 KB and double, up to 64 MB at a time, so a big stack needs few system calls and a small one stays small. Committed memory only uses RAM once it is written.
- Allocation is an aligned bump of the top, compared against a limit. Everything rare (committing, alignment above 4 KB, huge requests) is in a separate cold function, so the fast path stays a few instructions.
- Prefaulting (
TOPSTACK_PREFAULT) doesn't touch the fast path: the limit it compares against stops at a watermark half a window ahead, so crossing it takes the slow path, which sends the next window's request (onemadvise(MADV_POPULATE_WRITE)through a per-thread io_uring) and moves the watermark on. Memory freed by aScopeand used again isn't requested again. - Freeing moves the top back to a mark. Objects with destructors are recorded in a small list of cleanup notes, run newest first. Relay tables of the 64 KB regions that were freed completely are cleared at the same time.
- GrowBuf keeps its own copy of the top while it grows, and the stack's limit is set to zero so any other allocation on that stack takes the slow path and seals the buffer first. That is what makes "only the top grows" cheap to enforce.
- Stacks are lent by number: a 64-bit mask of which stacks are busy, and
countr_zeroto find the lowest free one, which is Goose's assignment rule done at runtime. Ref16relays: a far link stores a slot number; the slot lives in the table of the 64 KB region the link is in. The first 32 slots of every region are packed together (256 bytes per region); a region that needs more gets its own table. When a region's table is full, a slot whose link no longer refers to it is reused.
- Benchmarked on Linux only. macOS and Windows pass the tests in CI, but nothing
has been timed there. On Windows the tests that check that rule violations stop the
program don't run yet (they use
fork()). Stack sizes are rounded up to whole pages, which are 16 KB on Apple Silicon;reserved()gives the actual size. - A stack holds at most 2 GB, and reserves 16 GB of address space. That is
per-process virtual address space, not memory, and it doesn't affect other programs,
but tools that cap a process's address space (Valgrind,
ulimit -v, some containers) may refuse to create stacks. On Windows, each stack's small relay area (8 MB) counts toward the system commit limit, though it uses no RAM until written. - Rule violations are found at runtime, not compile time as in Goose. Link misuse
in release builds is only caught with
TOPSTACK_CHECKED_REFS;Ref16far links are always checked. AddressSanitizer doesn't yet know when aScopefrees memory, so it can't catch use after a rewind the way it catches use afterfree. failskips other destructors. It jumps withlongjmp, so astd::stringor a lock in a function betweencatch_fromandfailis left without its destructor running; only topstack's own objects are ended. Nothing checks this.- Records are plain structs, read as copies.
RecordBuffinds a struct's fields with a C++20 technique that works only for plain structs of up to 32 fields, and links can't be record fields. C++26 reflection would lift both limits. - No freeing out of order.
GrowBufcan drop its newest elements (truncate,clear), but there are no pools for objects that don't die in stack order (Goose'sslot_poolandslice_pool). - Memory isn't returned to the OS while a stack is alive, only when it is
destroyed (a
trim()is planned). - Strings and containers inside nodes use
mallocfor their contents unless they arestd::pmrcontainers given aStackResource. - One machine, one OS for the performance numbers so far, and results differ between
machines (
Link8againstRef16on tree; stack coloring's gain on blur showed on AMD, not on an Intel Xeon). GCC and Clang also differ a lot on some benchmarks, up to 5x where one vectorizes a loop and the other doesn't; the tables show the faster of the two.
- Compiler tools.
topstack-scopesfinds where Scopes go (see above). Next, a Clang plugin that checks topstack's rules at compile time, starting with links in local variables and temporaries, then "only the top grows", then narrow links where they can be proven to stay near. After that, an LLVM pass that passes the stack's top through calls in registers, as Goose does. - Safety: tell AddressSanitizer about rewinds, so use after a
Scopeis caught like use afterfree. - Speed: ports of the designs Goose is faster with (a CSR graph, a streaming respond).
- Library:
GrowBuf::popandresize, slot and slice pools,trim(), andRecordBufon C++26 reflection where compilers have it (any struct, any number of fields). - Real programs: cJSON is ported (see "A real library: cJSON"); next, a small C compiler (chibicc).
- Windows: the rule-violation tests, without
fork().
topstack's design follows Goose's data stacks,
relative references and stack assignment; the benchmark programs and their checksums
come from Goose's benchmark suite. Files copied from Goose (bench/bench.h, the
.goose programs and the C++ benchmark sources) are under the Apache License 2.0;
NOTICE lists them and the files based on them. See bench/LICENSE-goose.
topstack itself is released under the Apache License 2.0; see LICENSE and NOTICE.