Hash Table in C, C++, Java, Python and C#: Chaining, Open Addressing and Load Factor

How chaining and open addressing behave at four load factors, why deletion needs tombstones, and what a weak hash costs on 50,000 real-looking keys.

A wall of pigeonholes with one envelope per hole, one hole overflowing with a chain of envelopes, and one envelope about to be filed.

At 90% full, a linear-probing hash table reads about 55 slots to answer a lookup whose key is not there, against about 2.5 at 50% full. The jump comes from the load factor, not from a bad hash. A bad hash causes a different failure: on 50,000 realistic keys, hashing only the first byte left a longest chain of 7,034 entries, while FNV-1a kept the longest chain at 5.

This guide builds hash tables in C, C++, Java, Python and C# with two collision strategies, separate chaining and linear probing, and measures what each choice costs. It checks probe lengths against the textbook formulas, compares a weak hash with a good one on the same keys, measures the cost of deletion tombstones under churn, and benchmarks std::unordered_map with and without a reserve. Every program was compiled and run on Ubuntu 24.04 under WSL2 (GCC 13.3 and Clang 18.1.3, warnings as errors) and on Windows 11 (MSVC 19.44, Java 27, Python 3.14.6 and .NET 10). Every output block below is captured from a real run, and the code is in five GitHub repositories whose workflows build and test it. The definition assumes no hash table knowledge, and the measurements assume you have read the implementations.

What Is a Hash Table?

A hash table maps keys to values by computing an index from the key: a hash function turns each key into a bucket number, and the pair is stored in that bucket. Average lookup, insert and delete cost O(1) when the hash spreads keys evenly and the table keeps its load factor low. The worst case, when many keys collide, is O(n).

The array of buckets is the storage. A hash function converts a key, a string or a number, into a non-negative integer, and the bucket index is that integer modulo the bucket count. Two different keys can land in the same bucket, which is a collision, and the collision strategy is the design decision that separates one hash table from another. Separate chaining stores a list in each bucket and appends the colliding keys to it. Open addressing keeps one entry per slot and, when a slot is taken, probes forward in a fixed sequence until it finds an empty one.

The load factor is the number of stored entries divided by the number of slots. It is the number that governs cost: a chained table with a load factor of 1 stores one entry per bucket on average, and a linear-probing table near its capacity turns into a long cluster that every lookup has to walk. The implementations in this article keep the load factor at or below 0.75 by doubling the table when the next insert would pass it, and the measurements below show why that threshold is common.

A hash table is unordered. C++’s std::unordered_map, Java’s HashMap, Python’s dict and C#’s Dictionary<TKey,TValue> are the library versions. An ordered map, which keeps keys sorted and answers range queries, is a different structure, covered by the binary trees and B-tree articles. Hash tables win when the question is “what value belongs to this key?” and lose when it is “which keys lie between a and b?”. The C++ container is documented on cppreference as std::unordered_map.

Two ways to resolve a collision: a chain, or a probe Separate chaining: one list per bucket alice bob carol hash(k) buckets 0 1 alice 2 3 bob carol 4 5 bucket 3 holds two keys: the chain is walked on every lookup Open addressing: a probe sequence inside one array 0 1 alice 2 carol 3 dave 4 deleted 5 bob 6 7 hash(bob) = 2 The probe starts at the hash slot, steps forward past occupied slots and tombstones, and stops at an empty one.
Figure 1: Separate chaining keeps a list per bucket, so two keys that collide share a chain; open addressing keeps one array and resolves a collision by walking forward past occupied slots and tombstones to the next empty slot.

Hash Table Operations and Their Time Complexity

OperationWhat it doesAverageWorst case
put (insert)Adds a key, or replaces the value of an existing keyO(1) amortizedO(n), when keys collide or the insert triggers a rehash
get (lookup)Returns the value stored for a keyO(1)O(n), when the key’s bucket or probe run holds most keys
remove (delete)Removes a key and its valueO(1)O(n); open addressing leaves a tombstone
rehash (resize)Moves every live entry into a larger tableO(n) per rehash, O(1) amortized per insertO(n)
iterateVisits every entryO(n + m)O(n + m)
range queryFinds the keys between a and bNot supported: O(n + m) scanO(n + m)

In the table, n is the number of entries and m the number of buckets or slots. The average column assumes a hash that spreads the keys and a bounded load factor. The measurements below show what happens when either assumption fails.

How This Was Measured

SettingValue
Date testedNovember 30, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146, glibc 2.39; Windows 11 for the MSVC, Java and .NET builds
CompilersGCC 13.3 and Clang 18.1.3 at -O2 and -O3 through CMake Release; MSVC 19.44 at /W4 /WX
Language runtimesOpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404
Probe experiment100,000 distinct 32-bit keys from a fixed xorshift64 seed, and 100,000 absent keys from a second seed; load factors 0.25, 0.50, 0.75 and 0.90
Hash-quality experiment50,000 keys of the form first.last<N>@example.com, built from two fixed 64-name arrays; 131,072 buckets; three hash functions
Tombstone experiment131,072 slots, 98,304 initial keys at load factor 0.75, then four delete-and-reinsert rounds and one rebuild
Standard-library benchmark1,000,000 distinct int keys, insert plus lookup, median of 5 runs, std::unordered_map with default settings, with reserve, with max_load_factor(0.5) and the custom open-addressed map
What is timedThe insert and lookup calls and the probe work they do; key generation is outside the timed region for the benchmark, inside it for the probe experiment
StatisticAverages for probe counts; median of 5 runs for every timing, in milliseconds; heap figures are one run in bytes
CheckEvery timed program prints a checksum of the values it read, and the benchmark’s four maps must agree on it

No CPU pinning or frequency scaling control was used, and the host runs other software, so the timings are indicative for this machine and the ratios are the useful part. All timings and probe counts come from one machine and one WSL2 instance. The heap figures belong to glibc’s allocator on Ubuntu, which is why the builds check map behaviour and not heap bytes.

Chaining or Open Addressing?

The two strategies differ in where the collision lives. Chaining puts it in a second structure, a list hanging off the bucket. Open addressing puts it in the array itself, as a probe sequence that continues until an empty slot appears. The table below is the short version of the trade. The measurements later in the article fill in the numbers.

AspectSeparate chainingOpen addressing, linear probing
Where an entry livesA bucket array of list heads, plus one node per entryOne array of slots, with an empty, occupied or tombstone state
Load factor limitCan pass 1.0; performance degrades smoothlyMust stay below 1.0; probes lengthen sharply near the limit
Successful lookup costOne bucket plus half a chain: about 1 + a/2One probe at low load, worse as clusters merge: about half of (1 + 1/(1 – a))
Unsuccessful lookup costOne bucket: about a entries walkedAbout half of (1 + 1/(1 – a)^2); it grows fastest of all
DeletionUnlink one node; no marker neededMark a tombstone; clearing the slot breaks probe chains
Memory overheadA node per entry, usually a pointer and a headerA state byte or two per slot, plus spare slots below the load factor
Cache behaviourEach node is a separate allocation; a pointer chaseThe array is contiguous; the probe stays in one or two cache lines
GrowthRehash every entry into a new bucket arrayRehash every live entry and drop the tombstones
Typical userLibrary maps that must support deletion cheaplyCache-friendly maps, and textbooks that count probes

Chaining is the easier structure to implement and to delete from, and it tolerates a load factor above 1 without failing. Open addressing is the faster structure when the table fits in cache and the load factor stays modest, because the probe touches one array instead of chasing pointers, and its failure mode is aggressive: the unsuccessful lookup cost is what explodes near the load limit, while the successful one degrades more gently. The experiments measure both curves.

In the table, a is the load factor. The formulas are the textbook expectations the probe experiment tests against. The same hash-plus-list pairing appears in the LRU and FIFO cache simulator, where a hash table finds the entry and a linked list keeps the eviction order.

Hash Table Implementation in C

C has no map type in its standard library, so both versions below are complete programs. One stores string keys and int values in a chained table. The other stores int keys in an open-addressed table, so both collision strategies and the key shapes each suits appear side by side. Both grow the same way: start at 8 slots, double when the next insert would push the live entries past three quarters of the capacity, and rehash every live entry with the new capacity. The open-addressed map also counts its tombstones toward that threshold, for the reason the deletion section measures.

The Chained Map

typedef struct ChainNode {
    char              *key;    /* owned copy of the key                */
    int                value;
    struct ChainNode  *next;   /* next node in the same bucket         */
} ChainNode;

typedef struct {
    ChainNode **buckets;       /* heap array of capacity chain heads   */
    size_t      capacity;      /* number of buckets                    */
    size_t      live;          /* keys stored in the table             */
} ChainMap;

/* FNV-1a, 32 bit: cheap, and good enough to spread the demo's short keys. */
static uint32_t chain_hash(const char *key)
{
    uint32_t hash = 2166136261u;
    for (const unsigned char *p = (const unsigned char *)key; *p != '\0'; ++p) {
        hash ^= *p;
        hash *= 16777619u;
    }
    return hash;
}

/* Folds the 32-bit hash into 0 .. capacity - 1. The capacity is a power of
 * two, so the modulo compiles to a mask. */
static size_t chain_index(const ChainMap *map, const char *key)
{
    return (size_t)(chain_hash(key) & (uint32_t)(map->capacity - 1));
}

/* Returns the node holding key, or NULL. */
static ChainNode *chain_find(const ChainMap *map, const char *key)
{
    ChainNode *node = map->buckets[chain_index(map, key)];
    while (node != NULL) {
        if (strcmp(node->key, key) == 0)
            return node;
        node = node->next;
    }
    return NULL;
}

/* Doubles the bucket array and relinks every node at its new index. The node
 * objects and the key copies they own are reused, so nothing is duplicated.
 * Returns false without touching the table if the new array cannot be
 * allocated. */
static bool chain_grow(ChainMap *map)
{
    size_t new_capacity = map->capacity * 2;
    ChainNode **buckets = calloc(new_capacity, sizeof *buckets);
    if (buckets == NULL)
        return false;
    for (size_t i = 0; i < map->capacity; ++i) {
        ChainNode *node = map->buckets[i];
        while (node != NULL) {
            ChainNode *next = node->next;
            size_t index = (size_t)(chain_hash(node->key) &
                                    (uint32_t)(new_capacity - 1));
            node->next = buckets[index];
            buckets[index] = node;
            node = next;
        }
    }
    free(map->buckets);
    map->buckets = buckets;
    map->capacity = new_capacity;
    return true;
}
bool chain_put(ChainMap *map, const char *key, int value)
{
    ChainNode *node = chain_find(map, key);
    if (node != NULL) {
        node->value = value;
        return true;
    }
    if ((map->live + 1) > (map->capacity * 3) / 4) {
        if (!chain_grow(map))
            return false;
    }
    size_t key_length = strlen(key) + 1;
    char *copy = malloc(key_length);
    if (copy == NULL)
        return false;
    memcpy(copy, key, key_length);
    node = malloc(sizeof *node);
    if (node == NULL) {
        free(copy);
        return false;
    }
    size_t index = chain_index(map, copy);
    node->key = copy;
    node->value = value;
    node->next = map->buckets[index];
    map->buckets[index] = node;
    map->live++;
    return true;
}

Four details carry the correctness of this version. put walks the chain first and updates an existing key in place, so a duplicate insert neither grows the table nor lengthens the chain. The growth check runs only for a genuinely new key, and the rehash recomputes each key’s bucket with the new capacity instead of copying an old index. The capacity is a power of two, so the modulo compiles to a mask. remove unlinks the node and decrements the live count. free walks every bucket and every node, so a million-entry map is released without recursion.

The hash for strings is FNV-1a: start at 2166136261, multiply by 16777619 after XORing each byte. It uses every byte, mixes position into the result, and costs one multiplication per character, which is why it appears again in the hash-quality experiment.

The Open-Addressed Map

typedef enum {
    SLOT_EMPTY = 0,     /* never used since the last rehash            */
    SLOT_OCCUPIED = 1,  /* holds a live key                           */
    SLOT_TOMBSTONE = 2  /* held a key that was removed                */
} SlotState;

typedef struct {
    int          *keys;      /* key of an occupied slot               */
    int          *values;    /* value of an occupied slot             */
    unsigned char *states;   /* one SlotState per slot                */
    size_t        capacity;  /* number of slots                       */
    size_t        live;      /* occupied slots                        */
    size_t        tombstones;/* tombstone slots                       */
} OpenMap;

/* splitmix64's finalizer, truncated to 32 bits: a fixed mixing hash that
 * spreads consecutive or patterned integer keys. */
static uint32_t open_hash(int key)
{
    uint64_t x = (uint64_t)(uint32_t)key + 0x9e3779b97f4a7c15ULL;
    x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ULL;
    x = (x ^ (x >> 27)) * 0x94d049bb133111ebULL;
    x = x ^ (x >> 31);
    return (uint32_t)x;
}

static size_t open_start(const OpenMap *map, int key)
{
    return (size_t)(open_hash(key) % (uint32_t)map->capacity);
}

/* Searches for key. Returns true and writes the slot index to *slot when the
 * key is present. Stops only at an empty slot, as linear probing requires.
 * The loop runs at most capacity steps, so a corrupted table cannot hang. */
static bool open_find(const OpenMap *map, int key, size_t *slot)
{
    size_t start = open_start(map, key);
    for (size_t step = 0; step < map->capacity; ++step) {
        size_t index = (start + step) % map->capacity;
        if (map->states[index] == SLOT_EMPTY)
            return false;
        if (map->states[index] == SLOT_OCCUPIED && map->keys[index] == key) {
            *slot = index;
            return true;
        }
    }
    return false;
}

/* Writes key/value into the first slot that is not occupied, which is the
 * first tombstone met (reuse) or the first empty slot. The table always has
 * one of the two while live < capacity. */
static bool open_place(OpenMap *map, int key, int value)
{
    size_t start = open_start(map, key);
    for (size_t step = 0; step < map->capacity; ++step) {
        size_t index = (start + step) % map->capacity;
        if (map->states[index] != SLOT_OCCUPIED) {
            if (map->states[index] == SLOT_TOMBSTONE)
                map->tombstones--;
            map->states[index] = SLOT_OCCUPIED;
            map->keys[index] = key;
            map->values[index] = value;
            return true;
        }
    }
    return false;
}
bool open_remove(OpenMap *map, int key)
{
    size_t slot = 0;
    if (!open_find(map, key, &slot))
        return false;
    map->states[slot] = SLOT_TOMBSTONE;
    map->live--;
    map->tombstones++;
    return true;
}

The map stores its entries in three parallel arrays: keys, values and a one-byte state that is empty, occupied or tombstone. find hashes the key, then steps forward modulo capacity, skipping occupied slots that hold a different key and tombstones. It stops at an empty slot, which proves the key is absent.

put writes a new key into the first slot that is not occupied, so a tombstone on the probe path is reclaimed instead of using a fresh empty slot, and remove marks the slot as a tombstone. Before a new key goes in, put counts live entries plus tombstones: if the live entries alone would pass three quarters of the slots it doubles the table, and if only the tombstones push the total over, it rebuilds at the same size. Either rebuild re-inserts every occupied entry and drops every tombstone, so an empty slot always remains to end a probe. Every probe loop is bounded by the capacity, so a bug in the state handling cannot hang the program.

The C Demo

Two demo programs print one contract each. The chained map inserts five names, updates one, removes one, then bulk-inserts 100 keys to force five doublings:

Output:

chaining hash table
put alice 1, bob 2, carol 3, dave 4, eve 5 -> size 5
get bob -> 2
get frank -> missing
put bob 20 -> size 5
get bob -> 20
remove carol -> true, size 4
get carol -> missing
put key0 to key99 -> size 104, capacity 256
get key42 -> 42
get key142 -> missing

The open-addressed demo runs the same operations on integers, deletes one key and confirms that the map keeps answering the others. The deletion leaves a tombstone, and the tests check that a lookup for a key behind one still succeeds:

Output:

open addressing, linear probing, capacity 8
put 3, 11, 19, 4, 12 -> size 5
get 11 -> 11, get 19 -> 19
remove 11 -> true, size 4
get 19 -> 19
get 11 -> missing
put 27 -> size 5
put 0 to 99 -> size 100, capacity 256
get 42 -> 42
get 142 -> missing

Both outputs are byte-identical to the C++, Java, Python and C# programs. The capacity printed in the last lines is where the growth policy is checked: 104 live entries and 100 live entries both end at 256 slots, the power of two reached by doubling from 8 at a 0.75 threshold.

Hash Table Implementation in C++

In C++ the colliding chain or the probe sequence sits inside a class template, and the standard library already provides the production version. Both classes below take the key type, the value type and a hash functor, defaulting to std::hash<K>, and compare keys with operator==. A missing key is reported through std::optional<V> from get, so a value type is never confused with a missing entry.

ChainMap and OpenMap

template <typename K, typename V, typename Hash = std::hash<K>>
class ChainMap {
    struct Node {
        Node(const K& k, const V& v) : key(k), value(v) {}
        Node(const K& k, V&& v) : key(k), value(std::move(v)) {}

        K key;
        V value;
        std::unique_ptr<Node> next;
    };

public:
    using key_type = K;
    using mapped_type = V;
    using hash_type = Hash;

    ChainMap() : buckets_(kInitialCapacity) {}

    // Inserts the key, or overwrites the value if the key is already present.
    // An update never grows the table.
    void put(const K& key, const V& value) { put_impl(key, value); }
    void put(const K& key, V&& value) { put_impl(key, std::move(value)); }

    // Returns the value, or std::nullopt when the key is absent. This copies
    // the value, so it is available only when V is copy constructible; use
    // find() for move-only values.
    [[nodiscard]] std::optional<V> get(const K& key) const
    {
        const V* value = find(key);
        if (value == nullptr)
            return std::nullopt;
        return std::optional<V>(*value);
    }

    // Returns a pointer to the stored value, or nullptr when the key is absent.
    // The pointer is invalidated by the next put(), remove() or rehash.
    [[nodiscard]] const V* find(const K& key) const
    {
        for (const Node* node = buckets_[bucket_index(key)].get(); node != nullptr;
             node = node->next.get()) {
            if (node->key == key)
                return &node->value;
        }
        return nullptr;
    }
    template <typename ValueArg>
    void put_impl(const K& key, ValueArg&& value)
    {
        for (Node* node = buckets_[bucket_index(key)].get(); node != nullptr;
             node = node->next.get()) {
            if (node->key == key) {
                node->value = std::forward<ValueArg>(value);
                return;
            }
        }
        // The contract, in integer arithmetic: grow before inserting a new key
        // when the insert would push live entries / capacity above 0.75.
        if (size_ + 1 > (capacity() * 3) / 4)
            rehash(capacity() * 2);
        auto node = std::make_unique<Node>(key, std::forward<ValueArg>(value));
        const std::size_t index = bucket_index(key);
        node->next = std::move(buckets_[index]);
        buckets_[index] = std::move(node);
        ++size_;
    }

    // Recomputes every bucket index for the new capacity. Moves nodes, so the
    // old lists are unlinked one node at a time and never recursed through.
    void rehash(std::size_t new_capacity)
    {
        std::vector<std::unique_ptr<Node>> new_buckets(new_capacity);
        for (std::unique_ptr<Node>& head : buckets_) {
            while (head) {
                std::unique_ptr<Node> node = std::move(head);
                head = std::move(node->next);
                const std::size_t index = hash_(node->key) % new_capacity;
                node->next = std::move(new_buckets[index]);
                new_buckets[index] = std::move(node);
            }
        }
        buckets_.swap(new_buckets);
    }

The chained class keeps a std::vector of buckets, each bucket the head of a singly linked chain of std::unique_ptr nodes, and rehashes by moving every node into its bucket under the new capacity. Updates walk the chain first and overwrite the value, so they never grow the table.

template <typename K, typename V, typename Hash = std::hash<K>>
class OpenMap {
    enum class State : unsigned char { empty, occupied, tombstone };

public:
    using key_type = K;
    using mapped_type = V;
    using hash_type = Hash;

    OpenMap()
        : slots_(kInitialCapacity, State::empty),
          keys_(kInitialCapacity),
          values_(kInitialCapacity)
    {
    }

    // Inserts the key, or overwrites the value if the key is already present.
    // An update never grows the table.
    void put(const K& key, const V& value) { put_impl(key, value); }
    void put(const K& key, V&& value) { put_impl(key, std::move(value)); }

    // Returns the value, or std::nullopt when the key is absent. This copies
    // the value, so it is available only when V is copy constructible; use
    // find() for move-only values.
    [[nodiscard]] std::optional<V> get(const K& key) const
    {
        const V* value = find(key);
        if (value == nullptr)
            return std::nullopt;
        return std::optional<V>(*value);
    }

    // Returns a pointer to the stored value, or nullptr when the key is absent.
    // The pointer is invalidated by the next put(), remove() or rehash.
    [[nodiscard]] const V* find(const K& key) const
    {
        std::size_t index = 0;
        if (!find_existing(key, index))
            return nullptr;
        return &values_[index];
    }

    // Returns true if the key was present and is now removed. The slot becomes
    // a tombstone and its key and value are reset.
    bool remove(const K& key)
    {
        std::size_t index = 0;
        if (!find_existing(key, index))
            return false;
        slots_[index] = State::tombstone;
        keys_[index] = K{};
        values_[index] = V{};
        --size_;
        ++tombstones_;
        return true;
    }
    // Linear probe for an occupied slot whose key equals `key`. Stops only at
    // an empty slot, which also proves the key is absent; tombstones are walked
    // past. Bounded by one full wrap of the table.
    bool find_existing(const K& key, std::size_t& index) const
    {
        const std::size_t capacity = slots_.size();
        std::size_t slot = slot_index(key);
        std::size_t probes = 0;
        for (std::size_t step = 0; step < capacity; ++step) {
            ++probes;
            if (slots_[slot] == State::occupied && keys_[slot] == key) {
                note_probe(probes);
                index = slot;
                return true;
            }
            if (slots_[slot] == State::empty) {
                note_probe(probes);
                return false;
            }
            slot = (slot + 1) % capacity;
        }
        note_probe(probes);
        return false;
    }

    // Finds the slot a new key belongs in: the first tombstone on the probe
    // path if there is one, otherwise the empty slot that ends it. Returns
    // false when every slot is occupied or a tombstone, which the caller must
    // resolve with a rehash.
    bool find_insert_slot(const K& key, std::size_t& target) const
    {
        const std::size_t capacity = slots_.size();
        std::size_t slot = slot_index(key);
        std::size_t first_tombstone = kNoSlot;
        std::size_t probes = 0;
        for (std::size_t step = 0; step < capacity; ++step) {
            ++probes;
            if (slots_[slot] == State::empty) {
                note_probe(probes);
                target = (first_tombstone == kNoSlot) ? slot : first_tombstone;
                return true;
            }
            if (slots_[slot] == State::tombstone && first_tombstone == kNoSlot)
                first_tombstone = slot;
            slot = (slot + 1) % capacity;
        }
        note_probe(probes);
        return false;
    }

    template <typename ValueArg>
    void put_impl(const K& key, ValueArg&& value)
    {
        std::size_t index = 0;
        if (find_existing(key, index)) {
            values_[index] = std::forward<ValueArg>(value);
            return;
        }
        // The contract, in integer arithmetic: grow before inserting a new key
        // when the insert would push live entries / capacity above 0.75.
        // Tombstones count toward the threshold too: double when the live
        // entries need it, otherwise rebuild at the same size to drop them.
        const std::size_t limit = (capacity() * 3) / 4;
        if (size_ + 1 > limit)
            rehash(capacity() * 2);
        else if (size_ + tombstones_ + 1 > limit)
            rehash(capacity());
        // With tombstones counted this cannot fail; the loop is a safety net.
        std::size_t target = 0;
        while (!find_insert_slot(key, target))
            rehash(capacity() * 2);
        if (slots_[target] == State::tombstone)
            --tombstones_;                        // the insert reused the tombstone
        slots_[target] = State::occupied;
        keys_[target] = key;
        values_[target] = std::forward<ValueArg>(value);
        ++size_;
    }

The open-addressed class keeps parallel vectors for the slot state, the keys and the values, sized at construction, so an empty slot holds a default-constructed key and the key and value types must be default constructible and movable. find_existing walks past tombstones and stops only at an empty slot; find_insert_slot remembers the first tombstone for reuse; and put doubles when the live load would pass 0.75 and rebuilds at the same size when live entries plus tombstones would pass it, so the probe loop always finds an empty slot. The open-addressed class also records the longest probe sequence it sees, for the benchmark.

Both classes use std::hash<K> as given. For integers, libstdc++’s std::hash<int> returns the value unchanged, so keys that share their low bits would share a slot in a power-of-two table. The C version mixes integer keys with a splitmix64 finalizer for exactly this reason. The benchmark’s random keys do not trigger the problem, but a hash functor that mixes is the safer default for patterned keys.

The two classes also make the cost difference visible in the type system: the chained map allocates a node per entry, while the open map allocates none after growth and pays for spare slots instead. The benchmark later in the article measures both.

std::unordered_map, the Standard Container

For production C++, use std::unordered_map from <unordered_map>. Its interface exposes buckets and promises that references to elements survive a rehash, so the major implementations use separate chaining with one node per element. The load factor can exceed 1 without a failure, and the initial max_load_factor is 1.0. reserve(n) makes room for n elements up front and removes the rehash cost from the insert loop. max_load_factor(0.5f) asks for a shorter average chain at the cost of more buckets. bucket_count(), load_factor() and bucket_size(i), the length of one bucket’s chain, expose the state.

Two behaviours need care. operator[] inserts a default value when the key is missing, so a read through it mutates the map. find(), contains() (C++20) and at(), which throws std::out_of_range, read without inserting. And iteration order is unspecified and changes on rehash, so code that prints a map must sort or use an ordered container. The benchmark later in the article measures the default, reserved and low-load-factor versions against the custom open map.

The C++ Demo

Two demo programs print the same contract as the C programs. The chained demo builds a ChainMap<std::string, int>, updates one key, removes one and bulk-inserts 100 keys. The open demo does the same with OpenMap<int, int> and the tombstone sequence. Both outputs are compared byte for byte with the expected files on every build:

Output:

Chaining output:

chaining hash table
put alice 1, bob 2, carol 3, dave 4, eve 5 -> size 5
get bob -> 2
get frank -> missing
put bob 20 -> size 5
get bob -> 20
remove carol -> true, size 4
get carol -> missing
put key0 to key99 -> size 104, capacity 256
get key42 -> 42
get key142 -> missing

Open-addressing output:

open addressing, linear probing, capacity 8
put 3, 11, 19, 4, 12 -> size 5
get 11 -> 11, get 19 -> 19
remove 11 -> true, size 4
get 19 -> 19
get 11 -> missing
put 27 -> size 5
put 0 to 99 -> size 100, capacity 256
get 42 -> 42
get 142 -> missing

Hash Table Implementation in Java, Python and C#

The three versions that follow repeat the C design rather than the C++ one: a generic chained map and a generic open-addressed map, with the same growth policy and tombstone rules. Their library maps are the other half of the story: Java’s HashMap, Python’s dict and C#’s Dictionary<TKey,TValue> each make different implementation choices, and the differences are worth knowing when a program’s performance depends on them.

Java

public final class ChainMap<K, V> {
    private static final int INITIAL_CAPACITY = 8;

    private static final class Node<K, V> {
        final K key;
        V value;
        Node<K, V> next;   // the next node in the same bucket, or null at the end

        Node(K key, V value, Node<K, V> next) {
            this.key = key;
            this.value = value;
            this.next = next;
        }
    }

    private Node<K, V>[] buckets = newBuckets(INITIAL_CAPACITY);
    private int size;

    /**
     * Adds key with value, or replaces the value of an existing key. The bucket
     * array doubles when the new entry would push size above (capacity * 3) / 4.
     */
    public void put(K key, V value) {
        Objects.requireNonNull(key, "null keys are not supported");
        Objects.requireNonNull(value, "null values are not supported: get returns null for a missing key");
        int index = indexFor(key, buckets.length);
        for (Node<K, V> node = buckets[index]; node != null; node = node.next) {
            if (key.equals(node.key)) {
                node.value = value;   // an update never grows the table
                return;
            }
        }
        if (size + 1 > buckets.length * 3 / 4) {
            grow();
            index = indexFor(key, buckets.length);
        }
        buckets[index] = new Node<>(key, value, buckets[index]);
        size++;
    }
    public V get(K key) {
        Objects.requireNonNull(key, "null keys are not supported");
        for (Node<K, V> node = buckets[indexFor(key, buckets.length)]; node != null; node = node.next) {
            if (key.equals(node.key)) {
                return node.value;
            }
        }
        return null;
    }

    /** Removes key, returning true when it was present. */
    public boolean remove(K key) {
        Objects.requireNonNull(key, "null keys are not supported");
        int index = indexFor(key, buckets.length);
        Node<K, V> previous = null;
        for (Node<K, V> node = buckets[index]; node != null; previous = node, node = node.next) {
            if (key.equals(node.key)) {
                if (previous == null) {
                    buckets[index] = node.next;
                } else {
                    previous.next = node.next;
                }
                size--;
                return true;
            }
        }
        return false;
    }

The chained class uses key.hashCode() for the bucket and equals for the comparison, as every Java hash container does, and masks the hash with the power-of-two capacity. The open-addressed class repeats the parallel-array design. put rejects null values, so a null from get always means the key is missing. The growth step rebuilds every chain in the new bucket array instead of copying the old indices.

In application code, use java.util.HashMap. It starts with 16 buckets and a default load factor of 0.75, and rehashes to about twice the buckets when it passes that load. Unlike the class above, it allows a null key and null values, so containsKey is the way to tell a missing key from one mapped to null.

Its documentation warns that many keys with the same hashCode() slow any hash table down, and says that for Comparable keys the map may use their order to break ties. OpenJDK does this by turning a long bucket into a small red-black tree. Its iterators are fail-fast, its iteration order is unspecified, and it is not synchronized.

Python

def _grow_needed(live: int, capacity: int) -> bool:
    """True when one more live entry would push live / capacity above 0.75."""
    return (live + 1) > (capacity * 3) // 4


class ChainMap(Generic[K, V]):
    """A separate-chaining hash map with one list of pairs per bucket."""

    def __init__(self) -> None:
        self._buckets: list[list[tuple[K, V]]] = [
            [] for _ in range(_INITIAL_CAPACITY)
        ]
        self._live = 0

    def _bucket_index(self, key: K) -> int:
        return hash(key) % len(self._buckets)

    def _resize(self, new_capacity: int) -> None:
        """Double the bucket array and move every live entry to its new bucket."""
        entries = [entry for bucket in self._buckets for entry in bucket]
        self._buckets = [[] for _ in range(new_capacity)]
        for key, value in entries:
            self._buckets[hash(key) % new_capacity].append((key, value))

    def put(self, key: K, value: V) -> None:
        """Insert a new key or overwrite the value of an existing one."""
        bucket = self._buckets[self._bucket_index(key)]
        for index, (existing_key, _) in enumerate(bucket):
            if existing_key == key:
                bucket[index] = (key, value)
                return
        if _grow_needed(self._live, len(self._buckets)):
            self._resize(len(self._buckets) * 2)
        self._buckets[self._bucket_index(key)].append((key, value))
        self._live += 1

    def get(self, key: K) -> V | None:
        """Return the value for a key, or None when the key is missing."""
        for existing_key, value in self._buckets[self._bucket_index(key)]:
            if existing_key == key:
                return value
        return None

    def remove(self, key: K) -> bool:
        """Remove a key and report whether it was there."""
        bucket = self._buckets[self._bucket_index(key)]
        for index, (existing_key, _) in enumerate(bucket):
            if existing_key == key:
                bucket.pop(index)
                self._live -= 1
                return True
        return False

    def contains(self, key: K) -> bool:
        """Report whether the map holds the key."""
        bucket = self._buckets[self._bucket_index(key)]
        return any(existing_key == key for existing_key, _ in bucket)

    def size(self) -> int:
        """Return the number of live entries."""
        return self._live

    def capacity(self) -> int:
        """Return the number of buckets."""
        return len(self._buckets)

CPython’s dict is an open-addressed table with a compact entry array and a separate index array, which is how it keeps insertion order, a language guarantee since Python 3.7, and why the memory per entry is lower than a node per key. User-defined keys need only __hash__ and __eq__, and string hashing is randomized per process unless PYTHONHASHSEED is set. The dict documentation covers the interface.

The custom ChainMap and OpenMap in this article exist to show the mechanics, not to compete with dict. They use hash() and == like the built-in, return None for a missing key, and do not support None values, because None is the missing marker. The name ChainMap here means separate chaining. It is unrelated to collections.ChainMap, which groups several mappings into one view.

C#

public sealed class ChainMap<TKey, TValue>
    where TKey : notnull
{
    private sealed class Node
    {
        public Node(TKey key, TValue value)
        {
            Key = key;
            Value = value;
        }

        public TKey Key { get; }

        public TValue Value { get; set; }

        public Node? Next { get; set; }
    }

    private static readonly EqualityComparer<TKey> s_comparer = EqualityComparer<TKey>.Default;

    private Node?[] _buckets = new Node?[8];
    private int _count;

    /// <summary>Live entries in the map.</summary>
    public int Count => _count;

    /// <summary>Bucket slots. Starts at 8 and doubles; always a power of two.</summary>
    public int Capacity => _buckets.Length;

    /// <summary>Inserts a new key or overwrites the value of an existing one.</summary>
    public void Put(TKey key, TValue value)
    {
        ArgumentNullException.ThrowIfNull(key);
        ArgumentNullException.ThrowIfNull(value);

        int bucket = Bucket(key);
        for (Node? node = _buckets[bucket]; node is not null; node = node.Next)
        {
            if (s_comparer.Equals(node.Key, key))
            {
                node.Value = value;   // an update never grows the table
                return;
            }
        }

        // Grow before the new key goes in, never after: the demo's sizes and
        // the capacity it prints depend on this order.
        if (_count + 1 > (_buckets.Length * 3) / 4)
            Grow();

        bucket = Bucket(key);
        _buckets[bucket] = new Node(key, value) { Next = _buckets[bucket] };
        _count++;
    }
    /// <summary>
    /// Looks up a key. Returns false when the key is missing and leaves
    /// <paramref name="value"/> at its default value.
    /// </summary>
    public bool TryGet(TKey key, out TValue value)
    {
        ArgumentNullException.ThrowIfNull(key);
        for (Node? node = _buckets[Bucket(key)]; node is not null; node = node.Next)
        {
            if (s_comparer.Equals(node.Key, key))
            {
                value = node.Value;
                return true;
            }
        }
        value = default!;
        return false;
    }

    /// <summary>Removes a key. Returns false when the key is missing.</summary>
    public bool Remove(TKey key)
    {
        ArgumentNullException.ThrowIfNull(key);
        int bucket = Bucket(key);
        Node? previous = null;
        for (Node? node = _buckets[bucket]; node is not null; node = node.Next)
        {
            if (s_comparer.Equals(node.Key, key))
            {
                if (previous is null)
                    _buckets[bucket] = node.Next;
                else
                    previous.Next = node.Next;
                _count--;
                return true;
            }
            previous = node;
        }
        return false;
    }

The C# chained class uses EqualityComparer<TKey>.Default for both hashing and equality, which is what the base class library does, and the open-addressed class keeps the same parallel arrays. The custom class follows the library’s TryGetValue pattern with TryGet, which returns false and leaves the value at its default when the key is missing.

In application code, use System.Collections.Generic.Dictionary<TKey,TValue>. It stores entries in one array with a bucket index array and chains collisions through integer next indices rather than pointers, which keeps the entries compact. It resizes when the entry array fills. It is not thread-safe, ConcurrentDictionary<TKey,TValue> is the shared-access version, and its enumeration order is unspecified.

The Load Factor and the Length of a Probe

A probe is one slot examined. For chaining it is one node compared. For linear probing it is one array slot read. The two strategies have closed-form expectations, and the experiment runs both at the same four load factors, with the same 100,000 mixed keys and the same mixed hash for integers, then averages the probes over every key and over 100,000 keys that are not present.

static bool measure_open(size_t capacity, const uint32_t *keys,
                         double *hit, size_t *max_probe, double *miss)
{
    uint32_t *slots = malloc(capacity * sizeof *slots);
    unsigned char *occupied = calloc(capacity, sizeof *occupied);
    if (slots == NULL || occupied == NULL) {
        free(slots);
        free(occupied);
        return false;
    }
    for (size_t i = 0; i < KEY_COUNT; ++i) {
        size_t index = (size_t)(mix32(keys[i]) % (uint32_t)capacity);
        while (occupied[index])
            index = (index + 1) % capacity;
        occupied[index] = 1;
        slots[index] = keys[i];
    }

    double total = 0.0;
    size_t largest = 0;
    for (size_t i = 0; i < KEY_COUNT; ++i) {
        size_t index = (size_t)(mix32(keys[i]) % (uint32_t)capacity);
        size_t probes = 0;
        for (;;) {
            probes++;
            if (occupied[index] && slots[index] == keys[i])
                break;
            index = (index + 1) % capacity;
        }
        total += (double)probes;
        if (probes > largest)
            largest = probes;
    }
    *hit = total / (double)KEY_COUNT;
    *max_probe = largest;

    rng_seed(SEED_MISS);
    total = 0.0;
    size_t measured = 0;
    while (measured < (size_t)MISS_COUNT) {
        uint32_t key = next_key();
        size_t index = (size_t)(mix32(key) % (uint32_t)capacity);
        size_t probes = 0;
        bool found = false;
        for (;;) {
            probes++;
            if (!occupied[index])
                break;
            if (slots[index] == key) {
                found = true;           /* absent key drawn by accident */
                break;
            }
            index = (index + 1) % capacity;
        }
        if (!found) {
            total += (double)probes;
            measured++;
        }
    }
    *miss = total / (double)MISS_COUNT;
    free(slots);
    free(occupied);
    return true;
}

Output:

open addressing, linear probing, 100000 keys
load  hit  hit_theory  miss  miss_theory  max_probe
0.25  1.16 1.17        1.38  1.39         9
0.50  1.50 1.50        2.48  2.50         25
0.75  2.50 2.50        8.44  8.50         120
0.90  5.71 5.50        54.90 50.49        794
chaining, 100000 keys
load  hit  hit_theory  miss  miss_theory  max_chain
0.25  1.12 1.12        0.25  0.25         5
0.50  1.25 1.25        0.50  0.50         6
0.75  1.38 1.37        0.75  0.75         8
0.90  1.45 1.45        0.90  0.90         7
Average probes per lookup, measured against the textbook formulas successful lookup (probes) 0 1 2 3 4 5 6 0.25 0.50 0.75 0.90 unsuccessful lookup (probes) 0 10 20 30 40 50 0.25 0.50 0.75 0.90 load factor linear probing, measured chaining, measured textbook formula
Figure 2: Average probes per lookup measured at four load factors against the textbook formulas. Linear probing tracks the formulas for successful lookups but its unsuccessful probe length climbs steeply as the table fills; chaining stays close to its two formulas at every load factor.

Three things stand out in the output. The measured successful-lookup probes match the formula at every load factor for chaining, within 0.01, and for linear probing within 0.01 up to a load of 0.75 and within 0.21 at 0.90. The formulas are expectations for a random hash, and the mixed integer hash behaves like one.

The unsuccessful lookup is where linear probing separates: 2.48 probes at load 0.50, 8.44 at 0.75 and 54.90 at 0.90, against the formula’s 2.50, 8.50 and 50.49, while chaining’s miss cost is its load factor, 0.50, 0.75 and 0.90. The longest probe sequence tells the same story from the tail: 25 slots at 0.50, 120 at 0.75 and 794 at 0.90 for linear probing, against a longest chain of 6, 8 and 7 for chaining.

A single lookup near the load limit can therefore touch hundreds of slots, which is why the tables in this article grow at 0.75 rather than at 0.95. The measured miss value at 0.90 is 9% above the formula, the one place where the random-hash assumption is visibly stretched.

A Weak Hash and a Good Hash on the Same Keys

A hash function decides how the keys distribute before any collision strategy acts. Cryptographic hashing is a different job, covered by the MD5 and SHA article. A hash table needs speed, a wide output range and good mixing for its key shape. The experiment uses a set of 50,000 keys shaped like real email addresses, built from two fixed name arrays so the set is identical on every run, and hashes them into 131,072 buckets with a chained table. Three functions are compared: the first byte only, the sum of all bytes, and FNV-1a 32-bit, the variant specified in RFC 9923.

static uint32_t hash_first_byte(const char *key)
{
    return (uint32_t)(unsigned char)key[0];
}

static uint32_t hash_sum_bytes(const char *key)
{
    uint32_t sum = 0;
    for (const unsigned char *p = (const unsigned char *)key; *p != '\0'; ++p)
        sum += *p;
    return sum;
}

static uint32_t hash_fnv1a(const char *key)
{
    uint32_t hash = 2166136261u;
    for (const unsigned char *p = (const unsigned char *)key; *p != '\0'; ++p) {
        hash ^= *p;
        hash *= 16777619u;
    }
    return hash;
}
static bool run_hash(const char *label, HashFn hash,
                     char present[][MAX_KEY], char absent[][MAX_KEY])
{
    int *heads = malloc(BUCKETS * sizeof *heads);
    int *next = malloc(KEY_COUNT * sizeof *next);
    if (heads == NULL || next == NULL) {
        free(heads);
        free(next);
        return false;
    }
    for (size_t i = 0; i < (size_t)BUCKETS; ++i)
        heads[i] = -1;
    for (size_t i = 0; i < (size_t)KEY_COUNT; ++i) {
        size_t bucket = (size_t)(hash(present[i]) % (uint32_t)BUCKETS);
        next[i] = heads[bucket];
        heads[bucket] = (int)i;
    }

    size_t longest = 0;
    size_t non_empty = 0;
    double comparisons = 0.0;   /* every node is compared once per chain place */
    for (size_t i = 0; i < (size_t)BUCKETS; ++i) {
        size_t length = 0;
        for (int node = heads[i]; node >= 0; node = next[node])
            length++;
        if (length > 0) {
            non_empty++;
            comparisons += (double)length * (double)(length + 1) / 2.0;
        }
        if (length > longest)
            longest = length;
    }
    double average_chain = (double)KEY_COUNT / (double)non_empty;
    double hit = comparisons / (double)KEY_COUNT;

    double miss_sum = 0.0;
    for (size_t i = 0; i < (size_t)MISS_COUNT; ++i) {
        size_t bucket = (size_t)(hash(absent[i]) % (uint32_t)BUCKETS);
        size_t length = 0;
        for (int node = heads[bucket]; node >= 0; node = next[node])
            length++;
        miss_sum += (double)length;
    }
    double miss = miss_sum / (double)MISS_COUNT;

    printf("%-12s  %-9zu  %-9.2f  %-8.2f  %.2f\n",
           label, longest, average_chain, hit, miss);
    free(heads);
    free(next);
    return true;
}

Output:

keys 50000, buckets 131072, load 0.38
hash          max_chain  avg_chain  hit       miss
first-byte    7034       3125.00    2039.22   4069.16
sum-of-bytes  172        37.74      39.17     47.96
FNV-1a        5          1.20       1.19      0.38

The first-byte hash fails as expected: every key that starts with the same letter lands in one bucket. The longest chain holds 7,034 keys, the average 3,125, and a successful lookup compares 2,039 keys on average, which is the behaviour of a linked list with extra steps. Sum-of-bytes is better but still poor: a longest chain of 172, an average of 37.7 and 39.2 comparisons per hit, because the byte sum has a narrow range and no position information.

FNV-1a keeps the longest chain at 5, the average at 1.20 and the hit at 1.19, and its miss cost is 0.38 entries, about the 0.38 load factor. The worst and best longest chains differ by a factor of 1,407, and their average hit costs by a factor of 1,714. A hash that fails to use the whole key and mix it cannot be rescued by a better collision strategy.

A good hash only protects against keys that arrive by chance. When an attacker can choose the keys, as with HTTP parameters or JSON field names sent to a server, a fixed public hash such as FNV-1a can be fed thousands of keys that land in one bucket, turning every lookup into a list walk. The FNV specification itself does not recommend FNV where an active adversary is involved.

The standard libraries defend against this in different ways: CPython and .NET randomize string hashes per process, and Java’s HashMap can fall back on key order inside a crowded bucket when the keys are Comparable. A table that hashes untrusted input should rely on those defaults or use a keyed hash such as SipHash.

Deleting From an Open-Addressing Table

Deletion is where the two strategies diverge most. A chained table unlinks a node and is done. An open-addressing table cannot clear the slot, because a later lookup for a key that probed past that slot would stop at the empty one and miss. The slot has to become a tombstone, and the lookup has to treat a tombstone as “keep going” while remembering the first tombstone as a place a later insert may reuse.

static bool table_probe(const ChurnTable *table, uint32_t key,
                        size_t *probes)
{
    size_t index = (size_t)(mix32(key) % (uint32_t)table->capacity);
    for (size_t step = 0; step < table->capacity; ++step) {
        if (table->states[index] == STATE_EMPTY) {
            *probes = step + 1;
            return false;
        }
        if (table->states[index] == STATE_OCCUPIED &&
            table->keys[index] == key) {
            *probes = step + 1;
            return true;
        }
        index = (index + 1) % table->capacity;
    }
    *probes = table->capacity;
    return false;
}

/* Inserts a key that is known to be absent: the first slot that is not
 * occupied, a tombstone or an empty slot, takes it. */
static bool table_put_new(ChurnTable *table, uint32_t key)
{
    size_t index = (size_t)(mix32(key) % (uint32_t)table->capacity);
    for (size_t step = 0; step < table->capacity; ++step) {
        if (table->states[index] != STATE_OCCUPIED) {
            if (table->states[index] == STATE_TOMBSTONE)
                table->tombstones--;
            table->states[index] = STATE_OCCUPIED;
            table->keys[index] = key;
            table->live++;
            return true;
        }
        index = (index + 1) % table->capacity;
    }
    return false;
}

/* Averages the probes of a successful lookup of every live key and of an
 * unsuccessful lookup of ABSENT_KEYS keys that were never inserted. */
static void table_measure(const ChurnTable *table, double *hit, double *miss)
{
    double total = 0.0;
    for (size_t i = 0; i < table->capacity; ++i) {
        if (table->states[i] != STATE_OCCUPIED)
            continue;
        size_t probes = 0;
        table_probe(table, table->keys[i], &probes);
        total += (double)probes;
    }
    *hit = total / (double)table->live;

    rng_seed(SEED_ABSENT);
    total = 0.0;
    size_t measured = 0;
    while (measured < (size_t)ABSENT_KEYS) {
        uint32_t key = next_random();
        if (history_contains(key))
            continue;                  /* a used key is not an absent key */
        size_t probes = 0;
        if (table_probe(table, key, &probes)) {
            fprintf(stderr, "internal error: absent key is present\n");
            exit(EXIT_FAILURE);
        }
        total += (double)probes;
        measured++;
    }
    *miss = total / (double)ABSENT_KEYS;
}

Output:

open addressing, 131072 slots, linear probing
round  live    tombstones  hit   miss
start  98304   0           2.53  8.60
churn1 98304   9747        2.93  12.79
churn2 98304   16351       3.24  18.05
churn3 98304   20920       3.53  25.52
churn4 98304   24262       3.75  33.37
rehash 98304   0           2.52  9.05

Deletion leaves a cost behind. After the initial fill the table answers a missing key in 8.60 probes. After four delete-and-reinsert rounds it holds 24,262 tombstones and the same missing lookup costs 33.37 probes, 3.9 times more, while the successful lookup rises from 2.53 to 3.75 probes, 48% more. The live count never changes at 98,304, so the load factor stays at 0.75 and the formula would predict a constant 8.50. The tombstones are the whole difference.

Rebuilding the table from its live entries drops the tombstones and returns the miss cost to 9.05 probes, close to the initial 8.60. A table should rebuild when the tombstone count becomes a large fraction of the capacity, not only when the live count crosses the growth threshold.

The experiment’s table deliberately never rebuilds, so the cost stays visible. The open maps in the five repositories do rebuild: they count tombstones as used slots, and when live entries plus tombstones would pass three quarters of the capacity they rebuild at the same size, which keeps the miss cost near its starting value under any amount of churn.

std::unordered_map with and without a Reserve

The standard libraries hide these decisions behind defaults that are not always the ones a program needs. The benchmark inserts 1,000,000 distinct int keys into four maps, looks every key up, and reports the time and the bucket state. The heap is measured while the map holds all the entries.

int main()
{
    const std::vector<int> keys = make_keys();

    const std::size_t default_heap = heap_holding_default(keys);
    const std::size_t custom_heap = heap_holding_custom(keys);

    const Result default_result =
        median_run([&keys] { return run_std_once<Config::plain>(keys); });
    const Result reserved_result =
        median_run([&keys] { return run_std_once<Config::reserved>(keys); });
    const Result low_load_result =
        median_run([&keys] { return run_std_once<Config::load_half>(keys); });
    const Result custom_result =
        median_run([&keys] { return run_custom_once(keys); });

    if (default_result.checksum != reserved_result.checksum ||
        default_result.checksum != low_load_result.checksum ||
        default_result.checksum != custom_result.checksum) {
        std::fprintf(stderr, "checksum mismatch across the four maps\n");
        return EXIT_FAILURE;
    }

    std::printf("1,000,000 inserts + lookups, median of 5 runs (ms)\n");
    std::printf("%-31s%.1f  buckets %zu  load %.2f\n",
                "std::unordered_map, default", default_result.ms,
                default_result.buckets, default_result.load);
    std::printf("%-31s%.1f  buckets %zu  load %.2f\n",
                "std::unordered_map, reserved", reserved_result.ms,
                reserved_result.buckets, reserved_result.load);
    std::printf("%-31s%.1f  buckets %zu  load %.2f\n",
                "std::unordered_map, load 0.5", low_load_result.ms,
                low_load_result.buckets, low_load_result.load);
    std::printf("%-31s%.1f  capacity %zu  max_probe %zu\n",
                "custom open addressing", custom_result.ms,
                custom_result.capacity, custom_result.max_probe);
    std::printf("heap while holding 1,000,000 entries (bytes)\n");
    std::printf("std::unordered_map  %zu\n", default_heap);
    std::printf("custom open addressing  %zu\n", custom_heap);
    std::printf("checksum: %llu\n",
                static_cast<unsigned long long>(default_result.checksum));
    return EXIT_SUCCESS;
}

Output:

1,000,000 inserts + lookups, median of 5 runs (ms)
std::unordered_map, default    539.9  buckets 1447153  load 0.69
std::unordered_map, reserved   287.4  buckets 2144977  load 0.47
std::unordered_map, load 0.5   253.0  buckets 4026031  load 0.25
custom open addressing         268.5  capacity 2097152  max_probe 190
heap while holding 1,000,000 entries (bytes)
std::unordered_map  43579088
custom open addressing  18878544
checksum: 1073773607490123

The default map took 539.9 ms and ended with 1,447,153 buckets at a load of 0.69, after growing repeatedly from its initial bucket count. Calling reserve(2'000'000), room for twice the final entry count, cut the time to 287.4 ms and ended at 2,144,977 buckets at a load of 0.47. The reserve removed the growth path entirely. Lowering the load factor to 0.5 on top of the reserve took 253.0 ms, a further 12%, with 4,026,031 buckets at a load of 0.25.

The custom open-addressed map took 268.5 ms with 2,097,152 slots at a load of 0.48 and a longest probe of 190 over the whole run, inserts and rehashes included. It was 7% faster than the reserved standard map and 6% slower than the low-load one, while using 18,878,544 bytes against the standard map’s 43,579,088, 2.3 times less heap. The two results point in different directions: the library map with a reserve is close to the custom map in time, and the custom map’s compact arrays use less than half its memory.

Five Ways a Hash Table Passes a Quick Test and Still Fails

Each of these programs compiles cleanly with -Wall -Wextra -pedantic, and each prints something that looks plausible until the line below it. The four C programs live in the C repository’s pitfalls/ directory and the C++ one in the C++ repository’s. The workflows re-run each and assert the line that shows the bug.

1. Clearing the Slot on Delete

static void map_remove_clearing(ProbeMap *map, int key)
{
    size_t index = slot_for(key);
    while (map->states[index] == OCCUPIED) {
        if (map->keys[index] == key) {
            map->states[index] = EMPTY;
            map->live--;
            return;
        }
        index = (size_t)((index + 1) % (size_t)CAPACITY);
    }
}

/* Correct probing: stop only at a slot that was never occupied since the last
 * rehash. A cleared slot looks the same as one, which is the failure. */
static bool map_get(const ProbeMap *map, int key, int *out)
{
    size_t index = slot_for(key);
    while (map->states[index] == OCCUPIED) {
        if (map->keys[index] == key) {
            *out = map->keys[index];
            return true;
        }
        index = (size_t)((index + 1) % (size_t)CAPACITY);
    }
    return false;
}

Output:

clear_on_delete: clearing a deleted slot cuts the probe run
insert 3, 11, 19 -> slots 3, 4, 5
remove 11 -> true
get 19 -> missing, because slot 4 is now empty

The map removes 11 by clearing slot 4. Slot 5 still holds 19, but get(19) hashes to slot 3, finds 3, then finds slot 4 empty and stops, so a key that is in the table is reported missing. A tombstone at slot 4 would keep the probe alive, which is why the open map in this article marks removals instead of clearing them.

2. A Table That Ignores Its Tombstones

static bool map_put_ignoring_tombstones(ProbeMap *map, int key)
{
    size_t index = slot_for(key);
    for (size_t step = 0; step < (size_t)CAPACITY; ++step) {
        if (map->states[index] == OCCUPIED && map->keys[index] == key)
            return true;
        if (map->states[index] == EMPTY) {
            map->states[index] = OCCUPIED;
            map->keys[index] = key;
            map->empty--;
            map->live++;
            return true;
        }
        index = (index + 1) % (size_t)CAPACITY;
    }
    return false;                      /* no empty slot left: "full"      */
}

Output:

tombstone_full: inserts skip tombstones, so deletion space is lost
delete all 5 keys -> live 0, tombstones 5, empty 3
insert 8, 9, 10 -> live 3, tombstones 5, empty 0
insert 11 -> full true, live 3, tombstones 5

The insert routine treats a tombstone as occupied, so after deleting five keys each insert walks past the five tombstones and fills the three remaining empty slots. When those are used, the map reports full with three live entries and five tombstones. An insert must remember and reuse the first tombstone on its probe path, as open_place does.

3. Inserting the Same Key Twice

static bool map_put_buggy(ChainMap *map, const char *key, int value)
{
    if (map->used == (size_t)MAX_KEYS)
        return false;
    Node *node = &map->nodes[map->used++];
    node->key = key;
    node->value = value;
    node->next = NULL;
    size_t bucket = bucket_for(key);
    if (map->buckets[bucket] == NULL) {
        map->buckets[bucket] = node;
    } else {
        Node *tail = map->buckets[bucket];
        while (tail->next != NULL)
            tail = tail->next;
        tail->next = node;
    }
    map->size++;
    return true;
}

Output:

duplicate_key: chaining insert never checks for an existing key
put alice 1 -> size 1, chain length 1
put alice 2 -> size 2, chain length 2
get alice -> 1, expected 2

The buggy put appends a node without checking the chain, so alice is stored twice: size 2, chain length 2, and get reads the older value 1 while the caller expected 2. Every hash map must search before it inserts. The cost of that search is part of why the table keeps its load factor low.

4. Rehashing Without Remapping

static bool map_grow_stale(ChainMap *map)
{
    size_t new_capacity = map->capacity * 2;
    Node **buckets = calloc(new_capacity, sizeof *buckets);
    if (buckets == NULL)
        return false;
    for (size_t i = 0; i < map->capacity; ++i) {
        Node *node = map->buckets[i];
        while (node != NULL) {
            Node *next = node->next;
            node->next = buckets[i];   /* stale: should be new hash slot */
            buckets[i] = node;
            node = next;
        }
    }
    free(map->buckets);
    map->buckets = buckets;
    map->capacity = new_capacity;
    return true;
}

Output:

stale_rehash: growth keeps each key at its old bucket index
grow from 4 to 8 buckets -> size 4, capacity 8
get 10 -> 10
get 30 -> missing, though it is stored in old bucket 2

Growth allocates eight buckets but copies each node to its old bucket index. Key 10 still hashes to bucket 2 under both capacities and is found, but key 30 was in old bucket 2 and belongs in bucket 6 under the new capacity, so it is reported missing even though its node is in the table. Every rehash must recompute hash(key) % new_capacity.

5. Looking Up With std::unordered_map::operator[]

// operator_index.cpp - DO NOT COPY. std::unordered_map::operator[] on a missing
// key value-initializes the mapped value and inserts the key, so a read that
// looks like a lookup changes the size of the map. Use find() or at() instead.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic pitfalls/operator_index.cpp -o operator_index
#include <cstddef>
#include <iostream>
#include <string>
#include <unordered_map>

int main()
{
    std::unordered_map<std::string, int> word_counts;
    word_counts["alice"] = 1;

    std::cout << "operator_index: operator[] on a missing key\n";
    std::cout << "size before the lookup: " << word_counts.size() << '\n';
    std::cout << "count for frank through operator[]: " << word_counts["frank"]
              << '\n';
    std::cout << "size after the lookup: " << word_counts.size() << '\n';
}

Output:

operator_index: operator[] on a missing key
size before the lookup: 1
count for frank through operator[]: 0
size after the lookup: 2

Reading a missing key through operator[] inserts a default value: the size goes from 1 to 2 and the reported count for frank is 0. Use find(), contains() in C++20, or at() for a read. find returns end() without inserting anything, and at() throws std::out_of_range.

Key Takeaways

  • A hash table gives average O(1) insert, lookup and delete only while the hash spreads keys and the load factor stays low. Both conditions are measured here.
  • Linear probing tracks the textbook successful-lookup formula but its unsuccessful lookup cost climbs from 2.48 probes at load 0.50 to 54.90 at 0.90, while chaining misses cost only the load factor.
  • A weak hash fails before the collision strategy gets a chance: on 50,000 email-shaped keys the first-byte hash reached a longest chain of 7,034, against 5 for FNV-1a.
  • Deletion in an open-addressing table needs a tombstone, and tombstones lengthen later lookups until the table is rebuilt, and counting them toward the load factor triggers that rebuild automatically.
  • A duplicate insert must update the existing value, and a rehash must recompute each key’s bucket in the new table.
  • std::unordered_map resizes at a default max_load_factor of 1.0, and a reserve call cut the benchmark from 539.9 ms to 287.4 ms.
  • A fixed public hash such as FNV-1a is open to hash flooding when attackers choose the keys. Servers should rely on randomized or keyed hashing.

Frequently Asked Questions

Conclusion

The hash table is the structure whose worst case is decided before any code runs. A hash that uses the whole key and mixes it, a load factor that stays below its growth threshold, and a tombstone rule that keeps probe chains intact are the three decisions that keep insert, lookup and delete at average O(1). Each of them appeared here as a measured number: probe counts against the textbook formulas, a chain length of 7,034 against 5 on the same keys, and a missing-key lookup that grew 3.9 times under tombstone churn before a rebuild restored it.

In production code, use the library: std::unordered_map with a reserve, HashMap in Java, dict in Python and Dictionary<TKey,TValue> in C#, and reach for the hand-written versions when the probing or the memory layout has to be controlled. The data structures hub lists the structures that build on this one.

Source Code and Tests

All programs on this page are in the data-structures/hash-table directory of the five MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/hash-tableC hash table build status
C++mycplus/cpp-examples: data-structures/hash-tableC++ hash table build status
Javamycplus/java-examples: data-structures/hash-tableJava hash table build status
Pythonmycplus/python-examples: data-structures/hash-tablePython hash table build status
C#mycplus/csharp-examples: data-structures/hash-tableC# hash table build status

The C and C++ examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

Java runs with javac --release 17 -Xlint:all -Werror -d build src/*.java tests/*.java followed by java -ea -cp build MapTest; Python with python -m unittest discover -s tests -v; C# with dotnet build HashTable.slnx -c Release followed by dotnet run --project tests/MapTests -c Release --no-build.

What the builds check. Every demo’s stdout is compared byte for byte with the files in tests/expected/. The tests compare both maps against the standard library map over 100,000 random operations, including duplicate updates, missing keys, removals of absent keys, tombstone churn and at least five resizes, and they check that every value put and not removed is found. The C and C++ workflows also run the tests and demos under AddressSanitizer and UndefinedBehaviorSanitizer, and the C workflow re-runs the four pitfalls and checks the line each prints. The builds do not check the probe figures, the hash-quality figures or the timings: those belong to one machine and are captured with the article.

What I Verified

The example directories contain the test programs and the captured runs. The table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C, GCC 13.3Pass (8 of 8 tests)Not applicable
Build and tests, C, Clang 18.1.3Pass (8 of 8 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (8 of 8 tests)
Build and tests, C++, g++ 13.3Pass (5 of 5 tests)Not applicable
Build and tests, C++, clang++ 18.1.3Pass (5 of 5 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (4 of 4 tests; the benchmark is Linux only)
Java tests, JDK 21 on Ubuntu and JDK 27 on WindowsPass (all tests, two demo diffs)Pass (all tests, two demo diffs)
Python tests (3.12.3 on Ubuntu, 3.14.6 on Windows), ruff and mypy --strictPass (24 tests, two demo diffs, ruff and mypy clean)Pass (all tests, two demo diffs, ruff and mypy clean)
.NET build and tests (SDK 10.0.115 on Ubuntu, 10.0.404 on Windows)Pass (all tests, two demo diffs)Pass (all tests, two demo diffs)
AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ tests and demosPass (C 8 of 8, C++ 5 of 5)Not applicable
Five pitfalls, each caught by the check named in its sectionPass (4 C checks, 1 C++ check)Not applicable
Probe, hash-quality, tombstone and benchmark experimentsRun on Ubuntu 24.04, figures in the sections aboveNot run

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 locally (the CI matrix covers them), macOS, and timings on any other machine.

Scroll to Top