Performance

What It Costs to Know a Briton Has a Hundred Hit Points

Dec 1, 202613 min

In a game with a couple of thousand NPCs the most memory‑hungry data structure is not a mesh or a skeleton, not a physics collider and not even the navigation mesh, but a stat like health = 100. If you write it by the rules, the way C++ books teach you, it will take 880 bytes per character, make 14 allocations and spend 27 nanoseconds reading a single number, while the useful data in there still amounts to 20 bytes.

I’ll tell you how in one strategy game we turned 880 bytes into 64, got rid of the allocations and made the structures friends with the cache. It will probably help to know what a pointer is and what an allocation is, if you didn’t come from the C/C++ world, and to remember that a cache line on a modern CPU is 64 bytes and is read in its entirety even if you only needed one byte out of it, or worse, one bit, and maybe read up on what AoS and SoA are if you’ve somehow never run into those terms, and the rest you’ll find in the text.

So... why would a goat need an accordion at a funeral, or what was all this for? The project had a component that stored a small amount of arbitrary data for an entity (set, for example, by a designer in the editor), a classic character sheet:


name = "The One"
stats = {
    health = 100
    mana = 200
}
status_effects = {
    drunk = true
    delirious = true
}

Someone in a great hurry put this data into a stripped‑down JSON (it was convenient at the time the task was being done). This format only allows booleans, floats, strings, objects and arrays of numbers, the parser for it is also very simple and can be knocked together in a single evening, and this was some five years ago, so one can say with confidence that no Claude was harmed in the making of this masterpiece. Arbitrary arrays are banned too, and if you need a list of items, you make an object whose keys are GUIDs.

The ban looks like the format author just being difficult, but it is what it is, and by the whim of the author’s left heel our strings and arrays of numbers are considered monolithic, that is, indivisible when merging, and then any operation on the data boils down to “assign a value to such‑and‑such key”.

Which means two edits always merge predictably, and if a designer in the editor changed stats.health while a designer in another branch did something nasty to status_effects.drunk, merging both edits needs no conflict resolution and no waiting for review. Try doing the same with an arbitrary nested array where one person inserted an element in the middle and another deleted the third from the end, and you’ll quickly understand why arrays of objects never really caught on for configs like these.

Network code also benefits from this restriction, and the operation “assign a value to a key” is idempotent, meaning it can be sent, lost, resent and applied again without consequences, unlike “insert into an array”. We assume that a single entity has little data, there are many entities, and we care about both memory and speed, because a thousand NPCs on a level, each with its own sheet or property list or set of key‑value pairs, is our everyday case.

The naive approach

You can take the STL and describe a tree holding both strings and arrays, which gives us something like this:

enum class DataType { BOOL, FLOAT, STRING, OBJECT, ARRAY };

struct DataValue
{
    DataType type;
    union {
        bool b;
        float f;
        std::string *s;
        std::vector<float> *array;
        std::map<std::string, DataValue> *object;
    };
};

But this only looks good in theory, because suddenly the STL wants allocations for all this, both explicit ones (new std::string) and implicit ones inside string, inside vector and inside every node of std::map, which allocates a separate node with three pointers and a colour for every key‑value pair, and you end up with a five‑key character sheet that takes 880 bytes while actually storing only 20:

naive : allocs=14000 (14.0/entity)  bytes=880000 (880.0/entity)  lookup=27.0 ns/get

By today’s standards that’s pocket change, but even so the problem still shows up when a character has not one hundred such keys, and you’re lucky if it’s only a hundred and not closer to a thousand. And that’s when your std::map inside an entity, with its standard memory layout, starts to really affect frame time.

So... we get 880 bytes and 14 allocations for the sake of health, mana, two flags and a short name. And 27 nanoseconds per read is actually a very good result, because in my benchmark this whole thousand of config‑y configs fits entirely in cache and never really has to go out to RAM. To see what happens when the data doesn’t fit in cache, you have to run the same naive version on a hundred thousand components... I pulled the hundred thousand out of thin air, it’s just a nice number, and even so it was still faster than in the real game code:

naive tree : allocs=900000  bytes=54400000 (544 B/entity)
             sequential traversal     =  79..96 ns/get
             shuffled traversal       = 352..429 ns/get

So it took us four hundred nanoseconds to find out that one unfortunate Briton has a hundred hit points this frame. Now imagine this data is processed in order of distance to the player, or by LOD priority, or in whatever order the physics broadcast spat it out, meaning you practically never get it in address order, and shuffled access in such a system is not a pessimistic estimate but a way of life, so feel free to multiply that time by 2–3, because other systems of our own game will get in its way by periodically evicting it from the cache, which, again, nobody will tell you about until you go and look with your own eyes at why the FPS dropped.

Step 1: hashing the keys

The first insight about such a system comes when you’ve stared at it long enough in a debugger or a perf profiler... You realise that we never need the key strings themselves and we always either write a value by key or read a value by key, but never enumerate the keys to show them to the user, which means that instead of a string we can store its hash or something else, and since a single entity has few keys, 32, 16 and sometimes even 8 bits can be more than enough:

std::map<unsigned, DataValue> *object;

And with a flick of the wrist... the trousers turn into elegant shorts, that is, one allocation per key disappears, and together with the string go all the string comparisons during lookup, and comparing unsigned is something the CPU does much better and faster than even the shortest std::string.

But as you know, everything comes at a price, and now our memory dump contains 0x7a3c91f4, and nobody can tell any more that it used to be stats.health. So we add an extra “hash → string” table, which gets thrown out of the release build, and in the debug build we write a bit of code that expands hashes back into strings. You can do it right in Visual Studio’s natvis, and the average programmer won’t even notice, while collisions among a handful of keys of one entity we’ll fix by kicking the designers so they stop creating keys that collide.

Step 2: flattening the tree

The second insight comes after a week of trying to trick the STL map into running faster, and when someone on the team suggests storing not an object but just keys and values, it turns out the whole tree can be flattened, and instead of

name = "The One"
stats = { health = 100, mana = 200 }

we start storing

name = "The One" <<< this is already unsigned
stats.health = 100
stats.mana = 200

And we make the key stats.health an unsigned too, only we hash it not as the string stats.health but piece by piece. First stats on its own, then health on its own, then we mix the two hashes with yet another clever hash and get a new unique hash key, that’s the kind of clever hash maths it is.

Now the hierarchy exists only in the designer’s head and in the editor, and you can still read stats.health, but you can no longer ask such a map to “list everything in stats”. In practice, though, this turns out to be a workable option, because the code always knows which key it needs, and only the editor needs enumeration. Everything comes at a price, as you remember, so the editor gets a new data schema for character properties, but the whole property tree has turned into a flat array:

struct Entry
{
    unsigned key;
    DataType type;
    union {
        bool b;
        float f;
        std::string *s;
        std::vector<float> *array;
    };
};

std::vector<Entry> data;

Now there’s no lookup structure here at all, and to find a key you have to hop linearly through the array, which may sound like a step backwards and looks suspicious in code review, until you measure the perf numbers. And they say that a linear pass is cache‑friendly and at reasonable sizes (<1000) beats even the fastest std::map with its jumps around memory. You could also sort the keys and do a binary search, but at a hundred entries or fewer the fuss with sorting will cost more than the search itself.

naive      : allocs=14000 (14.0/ent) bytes=880000 (880.0/ent) lookup=27.0 ns/get
flat AoS   : allocs=6000  ( 6.0/ent) bytes=288000 (288.0/ent) lookup= 1.0 ns/get

And so our 880 bytes have turned into 288 and 14 allocations into 6, which gives us a lookup time of almost 1 ns on a hot cache with five keys.

Step 3: rewriting as SoA

Now we search for a key linearly, but along with the keys the cache also pulls in type and the value, which we don’t actually need during the search, and for every 16‑byte Entry record we have to haul extra bytes around, meaning three quarters of every cache line we read is just so much garbage that you have to load anyway. So we go further and split the array of structures into a structure of arrays.

std::vector<unsigned>  keys;
std::vector<DataType>  types;
std::vector<Value>     values;

Now during a search we read only keys, and a cache line fits sixteen entries instead of four, which in theory lets us hope for a fourfold speedup, but no:

variantlookup timereadallocations
AoS, 16 bytes per entry90…96 ns640 bytes, 10 cache lines6 per component
SoA, three std::vector87…105 ns160 bytes, 3 cache lines16 per component
std::map<unsigned,float>150…163 ns——

Four times as much data fits in the cache, but the time hasn’t changed, because it only looked pretty in theory, in articles about data‑oriented design. We really did read 160 bytes instead of 640, but those 160 bytes live in three different places in memory, and our three std::vectors will still be three independent allocations. So we traded one cache miss for three and gave the saved bandwidth back in the form of extra trips to memory.

Step 4: putting the arrays into one buffer

The red and blue lines are our third step, as they say, “spot the difference”

The red line (AoS) and the blue one (SoA on three vectors) run right next to each other across the whole sweep, now crossing, now drifting apart by a few percent. The yellow one at the top is the slow std::map for reference, and the green one at the bottom is where we’ll get to a bit later.

To get rid of the three allocations we’ll have to part with our beloved std::vector and make our own no less beloved vector3, with blackjack and ladies. If you look at how a vector is built inside, it’s something like this (simplified):

struct {
    int capacity;
    int size;
    unsigned *data;
};

which means our three vectors can be written as

int        capacity;
int        size;
unsigned  *keys;
DataType  *types;
Value     *values;

and notice that capacity and size are always the same for all three arrays and change at the same time, so one of each is enough for the whole structure. That means the arrays also grow and get reallocated together, which lets us allocate a single buffer and lay the data out one after another:

       -----------------------------------
buffer |   keys   |   types   |  values  |
       -----------------------------------
char *buffer = allocate(capacity * (sizeof(unsigned) + sizeof(DataType) + sizeof(Value)));
keys   = (unsigned *)buffer;
types  = (DataType *)(keys + capacity);
values = (Value *)(types + capacity);

Now SoA starts to show what the theory and the authors of DoD articles promise:

variantlookup timereadallocations
AoS, 16 bytes per entry90…96 ns640 bytes6
SoA, three std::vector87…105 ns160 bytes16
SoA in one buffer55…60 ns160 bytes1

Now we got a 1.6x gain in time and just one allocation instead of sixteen, and that’s our green line on the chart above. Steps 3 and 4 only work as a pair, and if you implement just the first one, you’ll spend a day refactoring and get zero perf, and a zero that added allocations on top of that.

The AI blackboard as a component

Before going further, it’s worth explaining why you’d even need a structure whose keys are set by someone other than the programmer. The character sheet is the most obvious case, the one I started the changes in the game engine with, but, to be honest, it’s a rare one. We do gain speed here on reading data, but it’s a few percent of the whole frame time.

It’s much more interesting to rework the AI blackboard — a mini table where a character (monster, NPC) keeps its current working parameters. It’s the same kind of per‑entity “key → value” table, home to threat.last_seen_pos, threat.confidence, nav.stuck_timer, squad.role, combat.reload_pending and hundreds of other keys that get added and thrown out over the course of development without touching C++. And this table is read every frame by every agent hundreds of times: on every tick the behaviour tree or state machine polls the blackboard to decide whether to shoot, run or stand still.

And this is where it becomes clear why I tortured the benchmark with shuffled access above. Two hundred agents are simply not traversed in the order of their addresses in memory, but in order of importance, or distance to the player, or by the lists handed out by the task scheduler. With the naive tree every blackboard poll costs ~400 nanoseconds, and at twenty accesses per tick per agent and two hundred agents that already comes to a millisecond and a half per frame spent purely on walking pointers. Not on making decisions, not on pathfinding, but simply on reading numbers that are already sitting in memory.

In previous articles about NavMesh and NPCs I showed how two hundred soldiers jam into a single gate and how an extra thousand path queries kill the frame... Here it’s the very same story, only about memory. The algorithm itself is fine, and everything dies on delivering the data to the algorithm.

Step 5: throwing out the STL

Our Value still holds pointers to STL types:

std::string        *s;
std::vector<float> *array;

They’ve outlived their usefulness at this stage, because the whole STL is built around separate allocations for every object. Plus there are still two levels of indirection here, first a pointer to the std::vector, then a pointer to the data inside it, so we reinvent our own wheel and replace them with home‑made equivalents:

struct { char *data; } s;
struct { int capacity; int size; float *data; } array;

We put all the strings and all the number arrays into one big buffer:

-------------------------------------------------------------
| "hello" | [0 1 3] | "mana" | [0 2] | ... free ........... |
-------------------------------------------------------------

And write a simple allocator for it:

struct ValueBuffer { char *p; unsigned capacity; unsigned size; };

void *allocate_memory(ValueBuffer &vb, unsigned size)
{
    if (vb.size + size > vb.capacity)
        return nullptr;                 // the caller reallocates a bigger buffer
    auto res = vb.p + vb.size;
    vb.size += size;
    return res;
}

This is an ordinary bump allocator that can only allocate and can’t free, so the buffer may run out of space, but it turns out you can live with that. There’s also a small problem if a value can change size, for example a designer changed the name from "The One" to "The One (deprecated, do not delete, ask Vasya)", and it no longer fits in its old place, then we have to allocate new space at the end, and a hole is left in the old spot:

-------------------------------------------------------------
| ....... | [0 1 3] | "mana" | [0 2] | "The One (depre..." |
-------------------------------------------------------------

Holes are fragmentation, and in a general‑purpose allocator that would be a problem, but now we pretty much couldn’t care less about it, even if it’s an unpleasant moment. We simply have few elements, and we control all the pointers to them ourselves, so at any moment we can shuffle the values around and defragment the buffer. But we don’t even need to do that, because fragmentation will simply at some point exhaust the buffer, the buffer will be reallocated, and the holes will vanish on their own during the copy. We get defragmentation for free, as a side effect of growth.

A general‑purpose allocator can’t do that, because it doesn’t know who references its blocks and from where, but we do. In general, knowing the structure of your data is the main source of gains in all this magic, which is why a specialised allocator showed up here and can do what a general one can’t. And not because it’s more cleverly written, it’s dirt‑cheap code knocked together on the knee, but because it knows everything about its data.

Step 6: compressing Value

Now all the value data lives in one buffer, which means it can be referenced not by a pointer but by an offset from the start of the buffer, and if a pointer on x64 is 8 bytes, an offset can be a plain int (4 bytes), and at our volumes even less, and then for short strings and arrays even 64 KB is more than enough, meaning offset and size together fit in 32(16) bits:

struct Data {
    uint16_t offset;
    uint16_t size;
};

struct Value {
    union {
        bool  b;
        float f;
        Data  data;   // for both strings and number arrays
    };
};

Value now takes 4 bytes instead of 8 in the STL version, but the main thing here isn’t the savings, because now we have offsets, which, unlike pointers, don’t need patching when the buffer moves, and the buffer can be moved anywhere, or copied, or compressed, or even written to disk and read back into another process at another address, and everything inside will stay valid.

sizeof: DataValue=16  Entry=16  Value=8  SlimValue=4
        std::map=16   std::string=32     std::vector=24

Step 7: merging the last two buffers

Almost there... we have two buffers left, the headers (keys and types) and the values (strings and arrays), and we want just one, to make it all properly pretty. So we naively put them one after the other:

--------------------------------------------------------
| Header      | Values     | ......... free .......... |
--------------------------------------------------------

But naive doesn’t work here, and the headers can’t grow without shifting the values, so we give each of them a bit of free space:

----------------------------------------------------------
| Header      | ....free.... | Values     | ....free.... |
----------------------------------------------------------

Now both can grow, but the free space is used inefficiently and the values hit their boundary while half of the headers’ reserve is still sitting empty, so we make an allocator that can grow data from both ends, I’ve already written about one like that:

----------------------------------------------------------
| Header      | ......... free .......... |     Values   |
----------------------------------------------------------

We allocate values not bottom‑up but top‑down, towards the headers, and now the free space is shared, and the buffer only needs reallocating when they meet in the middle. This is the same idea as the stack growing towards the heap, which you can see in the debugger in big programs, only local to a specific task.

What this gave us

naive      : allocs=14000 (14.0/ent) bytes=880000 (880.0/ent) live=880000
flat AoS   : allocs=6000  ( 6.0/ent) bytes=288000 (288.0/ent) live=128064
SoA        : allocs=16000 (16.0/ent) bytes=240000 (240.0/ent) live=110032
one buffer : allocs=1000  ( 1.0/ent) bytes=64000  ( 64.0/ent) live=64000
           : clone via memcpy = 0.5 ns/component
variantallocationsmemorysequentialshuffled
naive tree900 000544 B/entity79…96 ns352…429 ns
one buffer100 00064 B/entity4.1…5.9 ns9.4…10.1 ns

544 bytes turned into 64, nine allocations into one, 350–430 nanoseconds became 9.5. So the gain came out at roughly forty times on exactly the kind of access that happens in a real game.

The dashed lines (traversal in allocation order) sit at two to three nanoseconds and don’t grow at all, no matter how many components we added, because reading linearly is something the CPU does practically for free. The solid ones grow, but slowly, and at two hundred thousand they top out at ten nanoseconds versus six hundred for the tree.

But more interesting than the tables and the chart is what we got for free in the real game after rolling it out. The component no longer contains pointers, so it has become fully relocatable, and now a character sheet can be duplicated with a plain memcpy, and while we haven’t figured out yet what on earth that’s good for, it’s a very interesting thing.

Saving also got faster, since, as you’ve guessed, you can now just write the buffer to disk, and loading time improved too, because we removed the serialization code and the Serialize(Archive&) for every field.

It turned out to be a good fit for multiplayer as well, now a snapshot of the state of individual objects is just a buffer, and the snapshot from the previous tick is just another buffer, and keeping a twenty‑tick history for lag compensation suddenly becomes a question of a linear stretch of memory rather than of architecture and a separate database. And since all operations on the data boil down to “assign a value to a key”, the delta between two snapshots can be computed with a single pass over two key arrays.

But everything comes at a price... arithmetic over raw memory looks scary, you don’t get used to it right away and you can’t teach a designer to read it, and if you get distracted for a month you have to learn it all over again. So you have to write extra tools and viewers that pick it all apart, but once you’re used to reading unannotated memory you suddenly realise it’s simpler than a std::map<std::string, std::vector<std::string>>, where you can’t even tell how much memory you’re holding right now and where.

How it looks in big engines

If you think everything described here is exotica from a home‑grown engine, think again... As the saying goes, it’s all been stolen before us, and we should have just read the Unreal sources. In Unreal FName is step 1, where the string lives in a shared table, the structures store its index, and comparing names becomes comparing numbers. FInstancedStruct holds an arbitrary struct by value together with a pointer to its UScriptStruct, that is, without a separate wrapper object per instance. FArchive with its << is an attempt to do step 7 by hand for every field, but universal serialization is needed when the data is stuffed with pointers and can’t be moved around with a simple memcpy.

Unity DOTS has all of this too, and IComponentData must be an unmanaged struct and lives in a fixed‑size chunk together with a hundred others like it, which is steps 2–4 in the form of a compiler requirement. DynamicBuffer<T> is a variable‑length array living in the same chunk for as long as it stays small. And BlobAssetReference internally uses relative offsets instead of pointers, which repeats step 7 with the same justification, that a blob has to load from disk as is and work at any address.

The fundamental problem hasn’t changed

Twenty years ago on the PS2 programmers laid out data by hand across four kilobytes of scratchpad, because otherwise the CPU couldn’t pick it up from DMA in time. Now we have 64 gigabytes and an allocator we don’t have to write ourselves, but the problem is the same, and the data has to be arranged so that the CPU reads it linearly and goes out to memory as rarely as possible. Only the scale and the frame time have changed, and now you have to fit into 16 ms, which nobody notices until you’re down to ten frames a second.

All articles