Heterogeneous collections using compact handles

With this enum, and this index, I’ll organise your data, and I’ll optimise it for free!

— Q<uint>

You’ve got a closed set of heterogeneous types that operate in the same context. What do you use? Polymorphic inheritance or sum types, right?

Shared contexts don’t require shared memory layouts. Separate arrays and handles are often a better choice.

In pseudocode:

struct Entities {
    cats: Cat[];
    dogs: Dog[];
    bees: Bee[];
}

enum Kind : u8 {
    Cat,
    Dog,
    Bee,
}

bitfield Handle {
    kind:  Kind, 8;  // High bits
    index: u32,  24; // Low bits
}

Simple, fast, and debuggable.

Separate allocations allow elements to be stored with their native layout.

Inline sum types can incur significant waste due to member layouts and the tags. All elements must be sized to accommodate the largest member. Tags and alignment requirements can further increase the size.

The code below is an extreme example of inline sum type overheads (assuming natural alignment on x86-64). The tag only needs one byte but we pay eight due to alignment with B. With A active, 22 of the 24 bytes are wasted.

struct A {
    u8 x;
};

struct B {
    u64 x;
    u8 y;
};

tagged_union C {
    a: A,
    b: B,
}
Tagged union memory layout
Tagged union memory layout

The plot below compares memory usage for 10,000 elements between our tagged union and using individual arrays with a four-byte handle (container overheads omitted). Memory savings range from 16.7% to 79.2%, depending on element distribution.

Memory usage for 10,000 elements by type distribution
Memory usage for 10,000 elements by type distribution

Handles needn’t be pointer-sized. In some cases, a byte will do:

Kind bits Element bits Max kinds Max elements per kind
1 7 2 128
2 6 4 64
3 5 8 32
4 4 16 16
5 3 32 8
6 2 64 4
7 1 128 2

Unlike inline sum type tags, handles can be stored contiguously in an array. With the packed index and kind, there is little to no waste.

Processing elements requires only a loop and a switch statement.

fn transform_entities(entities: View<Entities>, handles: View<Handle>) -> void {
    for i in 0..handles.size() {
        var kind = handles[i].kind;
        var index = handles[i].index;

        switch (kind) {
        case Kind::Cat:
            process_cat(entities, index);
        case Kind::Dog:
            process_dog(entities, index);
        case Kind::Bee:
            process_bee(entities, index);
        }
    }
}

This flow control is simple for compilers to reason about. High-performance virtual dispatch relies on optimisations like speculative inlining in Java and devirtualisation in C++. Early implementations of C++’s std::visit emitted function pointer tables which added indirect call overheads and blocked inlining (unless the compiler could resolve the call targets).

If processing order doesn’t matter, we can do even better by sorting the handles. Their layout means sorting groups them by kind with ascending index order.

Sorting compact handles
Sorting compact handles

We can then process each kind in bulk:

fn transform_sorted_entities(entities: View<Entities>, handles: View<Handle>) -> void {
    // Assume handles are sorted

    var run_start = 0;

    while run_start < handles.size() {
        var kind = handles[run_start].kind;
        var run_end = run_start + 1;

        while run_end < handles.size() && handles[run_end].kind == kind {
            run_end += 1;
        }

        switch (kind) {
        case Kind::Cat:
            for i in run_start..run_end {
                process_cat(entities, handles[i].index);
            }
        case Kind::Dog:
            for i in run_start..run_end {
                process_dog(entities, handles[i].index);
            }
        case Kind::Bee:
            for i in run_start..run_end {
                process_bee(entities, handles[i].index);
            }
        }

        run_start = run_end;
    }
}

If the cost of sorting is acceptable, this can offer better instruction and data cache utilisation and fewer branch mispredictions.

When processing all elements of a given kind, we can iterate directly over the corresponding array.

For a real-world example, the table below shows Andrew Kelley’s benchmark results after reworking the Zig compiler’s frontend:

Metric Reduction
Wall-clock time 39%
Peak memory usage 40%
Cache misses 53%
Instructions executed 23%
CPU cycles 41%

Finally, debugging is easy because the data is right there in big dumb arrays. There’s no pointer chasing or special debugger support needed.

Conclusion

In my experience, this technique tends to have lower memory usage and higher performance than the more commonly used alternatives.

I harbour a suspicion that programming education contributes to these techniques’ underuse. Loops and arrays are introductory topics, with OOP and more complicated data structures taught later. Perhaps we conflate complexity with utility.

Quite often all you need is a big dumb array, a loop, and a switch statement.