TExcelTAD
Home › Game Engine Architecture in C++ › String Interning and IDs

String Interning and IDs

Games are full of names: asset paths (textures/rock_albedo.png), animation events (footstep_left), input actions (jump), material parameters (u_baseColor), sound banks, tags. Comparing and hashing std::strings every frame is slow, and storing thousands of copies of the same text wastes memory. Engines convert names into small integer IDs once, then compare integers.

There are two families:

Approach How Pros Cons
Hashed string ID id = hash(text), often at compile time no table needed to create one; works across processes and in saved data; free in switch-like code collisions are possible (rare with 64 bits, must be detected); reversing needs a debug table
Interned name a global table stores each unique string once; id = index no collisions; easy to print; compact (32-bit) the table must exist and be shared; IDs differ between runs, so never save them

Unreal's FName is an interned name; many engines (and Naughty Dog's well-known SID("...") macro) use hashed IDs.

Hashed IDs with FNV-1a

FNV-1a is a tiny, decent hash that is easy to make constexpr, so IDs written as literals cost nothing at runtime:

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <string_view>

constexpr std::uint64_t fnv1a(std::string_view s) {
    std::uint64_t h = 0xcbf29ce484222325ull;          // FNV offset basis
    for (char c : s) {
        h ^= static_cast<unsigned char>(c);
        h *= 0x100000001b3ull;                       // FNV prime
    }
    return h;
}

struct StringId {
    std::uint64_t value;
    constexpr bool operator==(const StringId&) const = default;
};

// consteval: the hash MUST be computed at compile time
consteval StringId operator""_sid(const char* s, std::size_t n) { return {fnv1a({s, n})}; }

// IDs are compile-time constants, so they can be checked at compile time
static_assert(fnv1a("jump") == "jump"_sid.value);

const char* describe(StringId event) {
    // compare against compile-time constants: one integer compare each
    if (event == "footstep_left"_sid || event == "footstep_right"_sid) return "play footstep sound";
    if (event == "jump"_sid) return "play jump sound";
    return "ignored";
}

int main() {
    std::printf("jump          = 0x%016llx\n", (unsigned long long)"jump"_sid.value);
    std::printf("Jump          = 0x%016llx\n", (unsigned long long)"Jump"_sid.value);
    std::printf("footstep_left = 0x%016llx\n", (unsigned long long)"footstep_left"_sid.value);

    // Runtime strings (from a file) hash to the same values
    const char* fromAnimFile[] = {"footstep_left", "jump", "land"};
    for (const char* e : fromAnimFile)
        std::printf("event %-14s -> %s\n", e, describe(StringId{fnv1a(e)}));
}
jump          = 0xeb1776ddf832a4cd
Jump          = 0x15a477e9f9a165ad
footstep_left = 0xd9d644c5a3f9b2f5
event footstep_left  -> play footstep sound
event jump           -> play jump sound
event land           -> ignored

Note that jump and Jump give completely different IDs. Decide once whether names are case-sensitive; if not, lower-case them before hashing, both at compile time and at runtime. Paths need the same treatment for slashes (\ vs /).

Detecting collisions

With 64-bit hashes a collision among a few hundred thousand names is astronomically unlikely, but with 32-bit hashes it is likely in any big project (the birthday bound is around 77 000 names for a 50 % chance). Either way, development builds keep a reverse table from ID to the first string seen, and complain when a different string produces the same ID. The same table lets the debugger and logs print names instead of numbers.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <string>
#include <string_view>
#include <unordered_map>

constexpr std::uint32_t fnv1a32(std::string_view s) {
    std::uint32_t h = 2166136261u;
    for (char c : s) { h ^= static_cast<unsigned char>(c); h *= 16777619u; }
    return h;
}

struct IdRegistry {                       // development builds only
    std::unordered_map<std::uint32_t, std::string> names;
    std::uint32_t intern(std::string_view s) {
        std::uint32_t id = fnv1a32(s);
        auto [it, inserted] = names.try_emplace(id, s);
        if (!inserted && it->second != s)
            std::printf("COLLISION: '%.*s' and '%s' both hash to 0x%08x\n", int(s.size()), s.data(),
                        it->second.c_str(), id);
        return id;
    }
    const char* name(std::uint32_t id) const {
        auto it = names.find(id);
        return it == names.end() ? "<unknown>" : it->second.c_str();
    }
};

int main() {
    IdRegistry reg;
    std::uint32_t a = reg.intern("player");
    std::uint32_t b = reg.intern("player");            // same string, same id: fine
    reg.intern("costarring");
    reg.intern("liquid");                              // a known FNV-1a 32-bit collision with "costarring"
    std::printf("player = 0x%08x, same id twice: %s\n", a, a == b ? "yes" : "no");
    std::printf("reverse lookup of 0x%08x: %s\n", a, reg.name(a));
    std::printf("reverse lookup of 0x12345678: %s\n", reg.name(0x12345678));
}
COLLISION: 'liquid' and 'costarring' both hash to 0x5e4daa9d
player = 0x2c99c300, same id twice: yes
reverse lookup of 0x2c99c300: player
reverse lookup of 0x12345678: <unknown>

Interned names

The other approach stores each distinct string once and hands out its index. Comparing two names is one integer compare, and the string can always be recovered. Because the index depends on the order in which names were first seen, interned IDs are only valid inside one process: save the text (or a stable hash) in files and network messages, never the index.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <deque>
#include <string>
#include <string_view>
#include <unordered_map>

class NameTable {
    std::deque<std::string> strings_;                         // deque: references stay valid as it grows
    std::unordered_map<std::string_view, std::uint32_t> lookup_;
public:
    std::uint32_t intern(std::string_view s) {
        if (auto it = lookup_.find(s); it != lookup_.end()) return it->second;
        strings_.emplace_back(s);
        auto id = std::uint32_t(strings_.size() - 1);
        lookup_.emplace(strings_.back(), id);                 // key views the stored copy
        return id;
    }
    std::string_view str(std::uint32_t id) const { return strings_[id]; }
    std::size_t size() const { return strings_.size(); }
};

struct Name {                                                 // 4 bytes, cheap to copy and compare
    std::uint32_t id;
    bool operator==(const Name&) const = default;
};

int main() {
    NameTable table;
    const char* tags[] = {"enemy", "flying", "enemy", "boss", "flying", "enemy"};
    for (const char* t : tags) {
        Name n{table.intern(t)};
        std::printf("%-6s -> id %u\n", t, n.id);
    }
    std::printf("%zu unique strings stored for %zu tags\n", table.size(), std::size(tags));
    std::printf("id 2 is '%.*s', sizeof(Name) = %zu\n", int(table.str(2).size()), table.str(2).data(), sizeof(Name));
}
enemy  -> id 0
flying -> id 1
enemy  -> id 0
boss   -> id 2
flying -> id 1
enemy  -> id 0
3 unique strings stored for 6 tags
id 2 is 'boss', sizeof(Name) = 4

Note: The string_view keys point into the deque, which never moves existing elements when it grows. A std::vector<std::string> would be a bug here: when it reallocates, short strings stored inline (small-string optimization) move, and every view into them dangles.

In a multithreaded engine the name table needs a lock (or a lock-free design) because loaders on worker threads intern names too. Unreal's FName table is exactly such a shared, append-only structure.

Test yourself

Why must interned-name indices never be written into save files?

  1. They are too large
  2. The index depends on the order names were first interned, which changes between runs
  3. Save files cannot hold integers
  4. They collide often

What does the consteval user-defined literal "jump"_sid guarantee?

  1. The hash is computed at runtime on first use
  2. The hash is computed at compile time, so the ID costs nothing at runtime
  3. The string is stored in the reverse table
  4. Collisions are impossible

Why does the development build keep a reverse table from hash to string?

  1. To make release builds faster
  2. To detect collisions and to print readable names in logs and the debugger
  3. Because hashing needs it
  4. To encrypt names