At 90% full, a linear-probing hash desk reads about 55 slots to reply a lookup whose key will not be there, in opposition to about 2.5 at 50% full. The bounce comes from the load issue, not from a nasty hash. A nasty hash causes a distinct failure: on 50,000 reasonable keys, hashing solely the primary byte left a longest chain of seven,034 entries, whereas FNV-1a saved the longest chain at 5.
This information builds hash tables in C, C++, Java, Python and C# with two collision methods, separate chaining and linear probing, and measures what every alternative prices. It checks probe lengths in opposition to the textbook formulation, compares a weak hash with a very good one on the identical keys, measures the price of deletion tombstones beneath churn, and benchmarks std::unordered_map with and and not using a reserve. Each program was compiled and run on Ubuntu 24.04 beneath WSL2 (GCC 13.3 and Clang 18.1.3, warnings as errors) and on Home windows 11 (MSVC 19.44, Java 27, Python 3.14.6 and .NET 10). Each output block beneath is captured from an actual run, and the code is in 5 GitHub repositories whose workflows construct and take a look at it. The definition assumes no hash desk information, and the measurements assume you’ve got learn the implementations.
What Is a Hash Desk?
A hash desk maps keys to values by computing an index from the important thing: a hash operate turns every key right into a bucket quantity, and the pair is saved in that bucket. Common lookup, insert and delete value O(1) when the hash spreads keys evenly and the desk retains its load issue low. The worst case, when many keys collide, is O(n).
The array of buckets is the storage. A hash operate converts a key, a string or a quantity, right into a non-negative integer, and the bucket index is that integer modulo the bucket rely. Two totally different keys can land in the identical bucket, which is a collision, and the collision technique is the design choice that separates one hash desk from one other. Separate chaining shops a checklist in every bucket and appends the colliding keys to it. Open addressing retains one entry per slot and, when a slot is taken, probes ahead in a hard and fast sequence till it finds an empty one.
The load issue is the variety of saved entries divided by the variety of slots. It’s the quantity that governs value: a chained desk with a load issue of 1 shops one entry per bucket on common, and a linear-probing desk close to its capability turns into an extended cluster that each lookup has to stroll. The implementations on this article hold the load issue at or beneath 0.75 by doubling the desk when the following insert would move it, and the measurements beneath present why that threshold is widespread.
A hash desk is unordered. C++’s std::unordered_map, Java’s HashMap, Python’s dict and C#’s Dictionary<TKey,TValue> are the library variations. An ordered map, which retains keys sorted and solutions vary queries, is a distinct construction, lined by the binary bushes and B-tree articles. Hash tables win when the query is “what worth belongs to this key?” and lose when it’s “which keys lie between a and b?”. The C++ container is documented on cppreference as std::unordered_map.
Hash Desk Operations and Their Time Complexity
| Operation | What it does | Common | Worst case |
|---|---|---|---|
| put (insert) | Provides a key, or replaces the worth of an present key | O(1) amortized | O(n), when keys collide or the insert triggers a rehash |
| get (lookup) | Returns the worth saved for a key | O(1) | O(n), when the important thing’s bucket or probe run holds most keys |
| take away (delete) | Removes a key and its worth | O(1) | O(n); open addressing leaves a tombstone |
| rehash (resize) | Strikes each stay entry into a bigger desk | O(n) per rehash, O(1) amortized per insert | O(n) |
| iterate | Visits each entry | O(n + m) | O(n + m) |
| vary question | Finds the keys between a and b | Not supported: O(n + m) scan | O(n + m) |
Within the desk, n is the variety of entries and m the variety of buckets or slots. The common column assumes a hash that spreads the keys and a bounded load issue. The measurements beneath present what occurs when both assumption fails.
How This Was Measured
| Setting | Worth |
|---|---|
| Date examined | November 30, 2026 |
| {Hardware} | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Home windows 11 Training construct 26300 |
| Working system | Ubuntu 24.04.5 beneath WSL2, kernel 5.15.146, glibc 2.39; Home windows 11 for the MSVC, Java and .NET builds |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 and -O3 by way of CMake Launch; MSVC 19.44 at /W4 /WX |
| Language runtimes | OpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404 |
| Probe experiment | 100,000 distinct 32-bit keys from a hard and fast xorshift64 seed, and 100,000 absent keys from a second seed; load components 0.25, 0.50, 0.75 and 0.90 |
| Hash-quality experiment | 50,000 keys of the shape first.final<N>@instance.com, constructed from two fastened 64-name arrays; 131,072 buckets; three hash capabilities |
| Tombstone experiment | 131,072 slots, 98,304 preliminary keys at load issue 0.75, then 4 delete-and-reinsert rounds and one rebuild |
| Customary-library benchmark | 1,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 customized open-addressed map |
| What’s timed | The insert and lookup calls and the probe work they do; key era is outdoors the timed area for the benchmark, inside it for the probe experiment |
| Statistic | Averages for probe counts; median of 5 runs for each timing, in milliseconds; heap figures are one run in bytes |
| Verify | Each timed program prints a checksum of the values it learn, and the benchmark’s 4 maps should agree on it |
No CPU pinning or frequency scaling management was used, and the host runs different software program, so the timings are indicative for this machine and the ratios are the helpful half. All timings and probe counts come from one machine and one WSL2 occasion. The heap figures belong to glibc’s allocator on Ubuntu, which is why the builds test map behaviour and never heap bytes.
Chaining or Open Addressing?
The 2 methods differ in the place the collision lives. Chaining places it in a second construction, a listing hanging off the bucket. Open addressing places it within the array itself, as a probe sequence that continues till an empty slot seems. The desk beneath is the quick model of the commerce. The measurements later within the article fill within the numbers.
| Facet | Separate chaining | Open addressing, linear probing |
|---|---|---|
| The place an entry lives | A bucket array of checklist heads, plus one node per entry | One array of slots, with an empty, occupied or tombstone state |
| Load issue restrict | Can move 1.0; efficiency degrades easily | Should keep beneath 1.0; probes lengthen sharply close to the restrict |
| Profitable lookup value | One bucket plus half a series: about 1 + a/2 | One probe at low load, worse as clusters merge: about half of (1 + 1/(1 – a)) |
| Unsuccessful lookup value | One bucket: a couple of entries walked | About half of (1 + 1/(1 – a)^2); it grows quickest of all |
| Deletion | Unlink one node; no marker wanted | Mark a tombstone; clearing the slot breaks probe chains |
| Reminiscence overhead | A node per entry, often a pointer and a header | A state byte or two per slot, plus spare slots beneath the load issue |
| Cache behaviour | Every node is a separate allocation; a pointer chase | The array is contiguous; the probe stays in a single or two cache strains |
| Development | Rehash each entry into a brand new bucket array | Rehash each stay entry and drop the tombstones |
| Typical consumer | Library maps that should assist deletion cheaply | Cache-friendly maps, and textbooks that rely probes |
Chaining is the better construction to implement and to delete from, and it tolerates a load issue above 1 with out failing. Open addressing is the sooner construction when the desk matches in cache and the load issue stays modest, as a result of the probe touches one array as an alternative of chasing pointers, and its failure mode is aggressive: the unsuccessful lookup value is what explodes close to the load restrict, whereas the profitable one degrades extra gently. The experiments measure each curves.
Within the desk, a is the load issue. The formulation are the textbook expectations the probe experiment exams in opposition to. The identical hash-plus-list pairing seems within the LRU and FIFO cache simulator, the place a hash desk finds the entry and a linked checklist retains the eviction order.
Hash Desk Implementation in C
C has no map sort in its commonplace library, so each variations beneath are full packages. One shops string keys and int values in a chained desk. The opposite shops int keys in an open-addressed desk, so each collision methods and the important thing shapes every fits seem aspect by aspect. Each develop the identical approach: begin at 8 slots, double when the following insert would push the stay entries previous three quarters of the capability, and rehash each stay entry with the brand new capability. The open-addressed map additionally counts its tombstones towards that threshold, for the rationale the deletion part measures.
The Chained Map
typedef struct ChainNode {
char *key; /* owned copy of the important thing */
int worth;
struct ChainNode *subsequent; /* subsequent node in the identical bucket */
} ChainNode;
typedef struct {
ChainNode **buckets; /* heap array of capability chain heads */
size_t capability; /* variety of buckets */
size_t stay; /* keys saved within the desk */
} ChainMap;
/* FNV-1a, 32 bit: low-cost, and adequate to unfold the demo's quick keys. */
static uint32_t chain_hash(const char *key)
{
uint32_t hash = 2166136261u;
for (const unsigned char *p = (const unsigned char *)key; *p != ' '; ++p) {
hash ^= *p;
hash *= 16777619u;
}
return hash;
}
/* Folds the 32-bit hash into 0 .. capability - 1. The capability is an influence of
* two, so the modulo compiles to a masks. */
static size_t chain_index(const ChainMap *map, const char *key)
{
return (size_t)(chain_hash(key) & (uint32_t)(map->capability - 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)];
whereas (node != NULL) {
if (strcmp(node->key, key) == 0)
return node;
node = node->subsequent;
}
return NULL;
}
/* Doubles the bucket array and relinks each node at its new index. The node
* objects and the important thing copies they personal are reused, so nothing is duplicated.
* Returns false with out touching the desk if the brand new array can't be
* allotted. */
static bool chain_grow(ChainMap *map)
{
size_t new_capacity = map->capability * 2;
ChainNode **buckets = calloc(new_capacity, sizeof *buckets);
if (buckets == NULL)
return false;
for (size_t i = 0; i < map->capability; ++i) {
ChainNode *node = map->buckets[i];
whereas (node != NULL) {
ChainNode *subsequent = node->subsequent;
size_t index = (size_t)(chain_hash(node->key) &
(uint32_t)(new_capacity - 1));
node->subsequent = buckets[index];
buckets[index] = node;
node = subsequent;
}
}
free(map->buckets);
map->buckets = buckets;
map->capability = new_capacity;
return true;
}
bool chain_put(ChainMap *map, const char *key, int worth)
{
ChainNode *node = chain_find(map, key);
if (node != NULL) {
node->worth = worth;
return true;
}
if ((map->stay + 1) > (map->capability * 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->worth = worth;
node->subsequent = map->buckets[index];
map->buckets[index] = node;
map->stay++;
return true;
}
4 particulars carry the correctness of this model. put walks the chain first and updates an present key in place, so a replica insert neither grows the desk nor lengthens the chain. The expansion test runs just for a genuinely new key, and the rehash recomputes every key’s bucket with the brand new capability as an alternative of copying an previous index. The capability is an influence of two, so the modulo compiles to a masks. take away unlinks the node and decrements the stay rely. free walks each bucket and each node, so a million-entry map is launched with out recursion.
The hash for strings is FNV-1a: begin at 2166136261, multiply by 16777619 after XORing every byte. It makes use of each byte, mixes place into the consequence, and prices one multiplication per character, which is why it seems once more within the hash-quality experiment.
The Open-Addressed Map
typedef enum {
SLOT_EMPTY = 0, /* by no means used for the reason that final rehash */
SLOT_OCCUPIED = 1, /* holds a stay key */
SLOT_TOMBSTONE = 2 /* held a key that was eliminated */
} SlotState;
typedef struct {
int *keys; /* key of an occupied slot */
int *values; /* worth of an occupied slot */
unsigned char *states; /* one SlotState per slot */
size_t capability; /* variety of slots */
size_t stay; /* occupied slots */
size_t tombstones;/* tombstone slots */
} OpenMap;
/* splitmix64's finalizer, truncated to 32 bits: a hard and fast 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->capability);
}
/* Searches for key. Returns true and writes the slot index to *slot when the
* key's current. Stops solely at an empty slot, as linear probing requires.
* The loop runs at most capability steps, so a corrupted desk can't hold. */
static bool open_find(const OpenMap *map, int key, size_t *slot)
{
size_t begin = open_start(map, key);
for (size_t step = 0; step < map->capability; ++step) {
size_t index = (begin + step) % map->capability;
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/worth into the primary slot that isn't occupied, which is the
* first tombstone met (reuse) or the primary empty slot. The desk all the time has
* one of many two whereas stay < capability. */
static bool open_place(OpenMap *map, int key, int worth)
{
size_t begin = open_start(map, key);
for (size_t step = 0; step < map->capability; ++step) {
size_t index = (begin + step) % map->capability;
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] = worth;
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 shops its entries in three parallel arrays: keys, values and a one-byte state that’s empty, occupied or tombstone. discover hashes the important thing, then steps ahead modulo capability, skipping occupied slots that maintain a distinct key and tombstones. It stops at an empty slot, which proves the hot button is absent.
put writes a brand new key into the primary slot that isn’t occupied, so a tombstone on the probe path is reclaimed as an alternative of utilizing a contemporary empty slot, and take away marks the slot as a tombstone. Earlier than a brand new key goes in, put counts stay entries plus tombstones: if the stay entries alone would move three quarters of the slots it doubles the desk, and if solely the tombstones push the whole over, it rebuilds on the similar dimension. Both rebuild re-inserts each occupied entry and drops each tombstone, so an empty slot all the time stays to finish a probe. Each probe loop is bounded by the capability, so a bug within the state dealing with can’t hold this system.
The C Demo
Two demo packages print one contract every. The chained map inserts 5 names, updates one, removes one, then bulk-inserts 100 keys to drive 5 doublings:
Output:
chaining hash desk
put alice 1, bob 2, carol 3, dave 4, eve 5 -> dimension 5
get bob -> 2
get frank -> lacking
put bob 20 -> dimension 5
get bob -> 20
take away carol -> true, dimension 4
get carol -> lacking
put key0 to key99 -> dimension 104, capability 256
get key42 -> 42
get key142 -> lacking
The open-addressed demo runs the identical operations on integers, deletes one key and confirms that the map retains answering the others. The deletion leaves a tombstone, and the exams test {that a} lookup for a key behind one nonetheless succeeds:
Output:
open addressing, linear probing, capability 8
put 3, 11, 19, 4, 12 -> dimension 5
get 11 -> 11, get 19 -> 19
take away 11 -> true, dimension 4
get 19 -> 19
get 11 -> lacking
put 27 -> dimension 5
put 0 to 99 -> dimension 100, capability 256
get 42 -> 42
get 142 -> lacking
Each outputs are byte-identical to the C++, Java, Python and C# packages. The capability printed within the final strains is the place the expansion coverage is checked: 104 stay entries and 100 stay entries each finish at 256 slots, the ability of two reached by doubling from 8 at a 0.75 threshold.
Hash Desk Implementation in C++
In C++ the colliding chain or the probe sequence sits inside a category template, and the usual library already supplies the manufacturing model. Each courses beneath take the important thing sort, the worth sort and a hash functor, defaulting to std::hash<Okay>, and examine keys with operator==. A lacking key’s reported by way of std::non-compulsory<V> from get, so a worth sort is rarely confused with a lacking entry.
ChainMap and OpenMap
template <typename Okay, typename V, typename Hash = std::hash<Okay>>
class ChainMap {
struct Node {
Node(const Okay& ok, const V& v) : key(ok), worth(v) {}
Node(const Okay& ok, V&& v) : key(ok), worth(std::transfer(v)) {}
Okay key;
V worth;
std::unique_ptr<Node> subsequent;
};
public:
utilizing key_type = Okay;
utilizing mapped_type = V;
utilizing hash_type = Hash;
ChainMap() : buckets_(kInitialCapacity) {}
// Inserts the important thing, or overwrites the worth if the hot button is already current.
// An replace by no means grows the desk.
void put(const Okay& key, const V& worth) { put_impl(key, worth); }
void put(const Okay& key, V&& worth) { put_impl(key, std::transfer(worth)); }
// Returns the worth, or std::nullopt when the hot button is absent. This copies
// the worth, so it's accessible solely when V is copy constructible; use
// discover() for move-only values.
[[nodiscard]] std::non-compulsory<V> get(const Okay& key) const
{
const V* worth = discover(key);
if (worth == nullptr)
return std::nullopt;
return std::non-compulsory<V>(*worth);
}
// Returns a pointer to the saved worth, or nullptr when the hot button is absent.
// The pointer is invalidated by the following put(), take away() or rehash.
[[nodiscard]] const V* discover(const Okay& key) const
{
for (const Node* node = buckets_[bucket_index(key)].get(); node != nullptr;
node = node->subsequent.get()) {
if (node->key == key)
return &node->worth;
}
return nullptr;
}
template <typename ValueArg>
void put_impl(const Okay& key, ValueArg&& worth)
{
for (Node* node = buckets_[bucket_index(key)].get(); node != nullptr;
node = node->subsequent.get()) {
if (node->key == key) {
node->worth = std::ahead<ValueArg>(worth);
return;
}
}
// The contract, in integer arithmetic: develop earlier than inserting a brand new key
// when the insert would push stay entries / capability above 0.75.
if (size_ + 1 > (capability() * 3) / 4)
rehash(capability() * 2);
auto node = std::make_unique<Node>(key, std::ahead<ValueArg>(worth));
const std::size_t index = bucket_index(key);
node->subsequent = std::transfer(buckets_[index]);
buckets_[index] = std::transfer(node);
++size_;
}
// Recomputes each bucket index for the brand new capability. Strikes nodes, so the
// previous lists are unlinked one node at a time and by no means recursed by way of.
void rehash(std::size_t new_capacity)
{
std::vector<std::unique_ptr<Node>> new_buckets(new_capacity);
for (std::unique_ptr<Node>& head : buckets_) {
whereas (head) {
std::unique_ptr<Node> node = std::transfer(head);
head = std::transfer(node->subsequent);
const std::size_t index = hash_(node->key) % new_capacity;
node->subsequent = std::transfer(new_buckets[index]);
new_buckets[index] = std::transfer(node);
}
}
buckets_.swap(new_buckets);
}
The chained class retains a std::vector of buckets, every bucket the top of a singly linked chain of std::unique_ptr nodes, and rehashes by shifting each node into its bucket beneath the brand new capability. Updates stroll the chain first and overwrite the worth, in order that they by no means develop the desk.
template <typename Okay, typename V, typename Hash = std::hash<Okay>>
class OpenMap {
enum class State : unsigned char { empty, occupied, tombstone };
public:
utilizing key_type = Okay;
utilizing mapped_type = V;
utilizing hash_type = Hash;
OpenMap()
: slots_(kInitialCapacity, State::empty),
keys_(kInitialCapacity),
values_(kInitialCapacity)
{
}
// Inserts the important thing, or overwrites the worth if the hot button is already current.
// An replace by no means grows the desk.
void put(const Okay& key, const V& worth) { put_impl(key, worth); }
void put(const Okay& key, V&& worth) { put_impl(key, std::transfer(worth)); }
// Returns the worth, or std::nullopt when the hot button is absent. This copies
// the worth, so it's accessible solely when V is copy constructible; use
// discover() for move-only values.
[[nodiscard]] std::non-compulsory<V> get(const Okay& key) const
{
const V* worth = discover(key);
if (worth == nullptr)
return std::nullopt;
return std::non-compulsory<V>(*worth);
}
// Returns a pointer to the saved worth, or nullptr when the hot button is absent.
// The pointer is invalidated by the following put(), take away() or rehash.
[[nodiscard]] const V* discover(const Okay& key) const
{
std::size_t index = 0;
if (!find_existing(key, index))
return nullptr;
return &values_[index];
}
// Returns true if the important thing was current and is now eliminated. The slot turns into
// a tombstone and its key and worth are reset.
bool take away(const Okay& key)
{
std::size_t index = 0;
if (!find_existing(key, index))
return false;
slots_[index] = State::tombstone;
keys_[index] = Okay{};
values_[index] = V{};
--size_;
++tombstones_;
return true;
}
// Linear probe for an occupied slot whose key equals `key`. Stops solely at
// an empty slot, which additionally proves the hot button is absent; tombstones are walked
// previous. Bounded by one full wrap of the desk.
bool find_existing(const Okay& key, std::size_t& index) const
{
const std::size_t capability = slots_.dimension();
std::size_t slot = slot_index(key);
std::size_t probes = 0;
for (std::size_t step = 0; step < capability; ++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) % capability;
}
note_probe(probes);
return false;
}
// Finds the slot a brand new key belongs in: the primary tombstone on the probe
// path if there may be one, in any other case the empty slot that ends it. Returns
// false when each slot is occupied or a tombstone, which the caller should
// resolve with a rehash.
bool find_insert_slot(const Okay& key, std::size_t& goal) const
{
const std::size_t capability = slots_.dimension();
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 < capability; ++step) {
++probes;
if (slots_[slot] == State::empty) {
note_probe(probes);
goal = (first_tombstone == kNoSlot) ? slot : first_tombstone;
return true;
}
if (slots_[slot] == State::tombstone && first_tombstone == kNoSlot)
first_tombstone = slot;
slot = (slot + 1) % capability;
}
note_probe(probes);
return false;
}
template <typename ValueArg>
void put_impl(const Okay& key, ValueArg&& worth)
{
std::size_t index = 0;
if (find_existing(key, index)) {
values_[index] = std::ahead<ValueArg>(worth);
return;
}
// The contract, in integer arithmetic: develop earlier than inserting a brand new key
// when the insert would push stay entries / capability above 0.75.
// Tombstones rely towards the edge too: double when the stay
// entries want it, in any other case rebuild on the similar dimension to drop them.
const std::size_t restrict = (capability() * 3) / 4;
if (size_ + 1 > restrict)
rehash(capability() * 2);
else if (size_ + tombstones_ + 1 > restrict)
rehash(capability());
// With tombstones counted this can't fail; the loop is a security internet.
std::size_t goal = 0;
whereas (!find_insert_slot(key, goal))
rehash(capability() * 2);
if (slots_[target] == State::tombstone)
--tombstones_; // the insert reused the tombstone
slots_[target] = State::occupied;
keys_[target] = key;
values_[target] = std::ahead<ValueArg>(worth);
++size_;
}
The open-addressed class retains parallel vectors for the slot state, the keys and the values, sized at development, so an empty slot holds a default-constructed key and the important thing and worth varieties have to be default constructible and movable. find_existing walks previous tombstones and stops solely at an empty slot; find_insert_slot remembers the primary tombstone for reuse; and put doubles when the stay load would move 0.75 and rebuilds on the similar dimension when stay entries plus tombstones would move it, so the probe loop all the time finds an empty slot. The open-addressed class additionally data the longest probe sequence it sees, for the benchmark.
Each courses use std::hash<Okay> as given. For integers, libstdc++’s std::hash<int> returns the worth unchanged, so keys that share their low bits would share a slot in a power-of-two desk. The C model mixes integer keys with a splitmix64 finalizer for precisely this motive. The benchmark’s random keys don’t set off the issue, however a hash functor that mixes is the safer default for patterned keys.
The 2 courses additionally make the price distinction seen within the sort system: the chained map allocates a node per entry, whereas the open map allocates none after progress and pays for spare slots as an alternative. The benchmark later within the article measures each.
std::unordered_map, the Customary Container
For manufacturing C++, use std::unordered_map from <unordered_map>. Its interface exposes buckets and guarantees that references to components survive a rehash, so the key implementations use separate chaining with one node per component. The load issue can exceed 1 and not using a failure, and the preliminary max_load_factor is 1.0. reserve(n) makes room for n components up entrance and removes the rehash value from the insert loop. max_load_factor(0.5f) asks for a shorter common chain at the price of extra buckets. bucket_count(), load_factor() and bucket_size(i), the size of 1 bucket’s chain, expose the state.
Two behaviours want care. operator[] inserts a default worth when the hot button is lacking, so a learn by way of it mutates the map. discover(), comprises() (C++20) and at(), which throws std::out_of_range, learn with out inserting. And iteration order is unspecified and adjustments on rehash, so code that prints a map should kind or use an ordered container. The benchmark later within the article measures the default, reserved and low-load-factor variations in opposition to the customized open map.
The C++ Demo
Two demo packages print the identical contract because the C packages. The chained demo builds a ChainMap<std::string, int>, updates one key, removes one and bulk-inserts 100 keys. The open demo does the identical with OpenMap<int, int> and the tombstone sequence. Each outputs are in contrast byte for byte with the anticipated information on each construct:
Output:
Chaining output:
chaining hash desk
put alice 1, bob 2, carol 3, dave 4, eve 5 -> dimension 5
get bob -> 2
get frank -> lacking
put bob 20 -> dimension 5
get bob -> 20
take away carol -> true, dimension 4
get carol -> lacking
put key0 to key99 -> dimension 104, capability 256
get key42 -> 42
get key142 -> lacking
Open-addressing output:
open addressing, linear probing, capability 8
put 3, 11, 19, 4, 12 -> dimension 5
get 11 -> 11, get 19 -> 19
take away 11 -> true, dimension 4
get 19 -> 19
get 11 -> lacking
put 27 -> dimension 5
put 0 to 99 -> dimension 100, capability 256
get 42 -> 42
get 142 -> lacking
Hash Desk Implementation in Java, Python and C#
The three variations that observe repeat the C design reasonably than the C++ one: a generic chained map and a generic open-addressed map, with the identical progress coverage and tombstone guidelines. Their library maps are the opposite half of the story: Java’s HashMap, Python’s dict and C#’s Dictionary<TKey,TValue> every make totally different implementation decisions, and the variations are value realizing when a program’s efficiency is dependent upon them.
Java
public last class ChainMap<Okay, V> {
non-public static last int INITIAL_CAPACITY = 8;
non-public static last class Node<Okay, V> {
last Okay key;
V worth;
Node<Okay, V> subsequent; // the following node in the identical bucket, or null on the finish
Node(Okay key, V worth, Node<Okay, V> subsequent) {
this.key = key;
this.worth = worth;
this.subsequent = subsequent;
}
}
non-public Node<Okay, V>[] buckets = newBuckets(INITIAL_CAPACITY);
non-public int dimension;
/**
* Provides key with worth, or replaces the worth of an present key. The bucket
* array doubles when the brand new entry would push dimension above (capability * 3) / 4.
*/
public void put(Okay key, V worth) {
Objects.requireNonNull(key, "null keys should not supported");
Objects.requireNonNull(worth, "null values should not supported: get returns null for a lacking key");
int index = indexFor(key, buckets.size);
for (Node<Okay, V> node = buckets[index]; node != null; node = node.subsequent) {
if (key.equals(node.key)) {
node.worth = worth; // an replace by no means grows the desk
return;
}
}
if (dimension + 1 > buckets.size * 3 / 4) {
develop();
index = indexFor(key, buckets.size);
}
buckets[index] = new Node<>(key, worth, buckets[index]);
dimension++;
}
public V get(Okay key) {
Objects.requireNonNull(key, "null keys should not supported");
for (Node<Okay, V> node = buckets[indexFor(key, buckets.length)]; node != null; node = node.subsequent) {
if (key.equals(node.key)) {
return node.worth;
}
}
return null;
}
/** Removes key, returning true when it was current. */
public boolean take away(Okay key) {
Objects.requireNonNull(key, "null keys should not supported");
int index = indexFor(key, buckets.size);
Node<Okay, V> earlier = null;
for (Node<Okay, V> node = buckets[index]; node != null; earlier = node, node = node.subsequent) {
if (key.equals(node.key)) {
if (earlier == null) {
buckets[index] = node.subsequent;
} else {
earlier.subsequent = node.subsequent;
}
size--;
return true;
}
}
return false;
}
The chained class makes use of key.hashCode() for the bucket and equals for the comparability, as each Java hash container does, and masks the hash with the power-of-two capability. The open-addressed class repeats the parallel-array design. put rejects null values, so a null from get all the time means the hot button is lacking. The expansion step rebuilds each chain within the new bucket array as an alternative of copying the previous indices.
In utility code, use java.util.HashMap. It begins with 16 buckets and a default load issue of 0.75, and rehashes to about twice the buckets when it passes that load. Not like the category above, it permits a null key and null values, so containsKey is the way in which to inform a lacking key from one mapped to null.
Its documentation warns that many keys with the identical hashCode() gradual any hash desk down, and says that for Comparable keys the map could use their order to interrupt ties. OpenJDK does this by turning an extended bucket right into a small red-black tree. Its iterators are fail-fast, its iteration order is unspecified, and it’s not synchronized.
Python
def _grow_needed(stay: int, capability: int) -> bool:
"""True when yet another stay entry would push stay / capability above 0.75."""
return (stay + 1) > (capability * 3) // 4
class ChainMap(Generic[K, V]):
"""A separate-chaining hash map with one checklist of pairs per bucket."""
def __init__(self) -> None:
self._buckets: checklist[list[tuple[K, V]]] = [
[] for _ in vary(_INITIAL_CAPACITY)
]
self._live = 0
def _bucket_index(self, key: Okay) -> int:
return hash(key) % len(self._buckets)
def _resize(self, new_capacity: int) -> None:
"""Double the bucket array and transfer each stay entry to its new bucket."""
entries = [entry for bucket in self._buckets for entry in bucket]
self._buckets = [[] for _ in vary(new_capacity)]
for key, worth in entries:
self._buckets[hash(key) % new_capacity].append((key, worth))
def put(self, key: Okay, worth: V) -> None:
"""Insert a brand new key or overwrite the worth of an present one."""
bucket = self._buckets[self._bucket_index(key)]
for index, (existing_key, _) in enumerate(bucket):
if existing_key == key:
bucket[index] = (key, worth)
return
if _grow_needed(self._live, len(self._buckets)):
self._resize(len(self._buckets) * 2)
self._buckets[self._bucket_index(key)].append((key, worth))
self._live += 1
def get(self, key: Okay) -> V | None:
"""Return the worth for a key, or None when the hot button is lacking."""
for existing_key, worth in self._buckets[self._bucket_index(key)]:
if existing_key == key:
return worth
return None
def take away(self, key: Okay) -> bool:
"""Take away a key and report whether or not 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 comprises(self, key: Okay) -> bool:
"""Report whether or not the map holds the important thing."""
bucket = self._buckets[self._bucket_index(key)]
return any(existing_key == key for existing_key, _ in bucket)
def dimension(self) -> int:
"""Return the variety of stay entries."""
return self._live
def capability(self) -> int:
"""Return the variety of buckets."""
return len(self._buckets)
CPython’s dict is an open-addressed desk with a compact entry array and a separate index array, which is the way it retains insertion order, a language assure since Python 3.7, and why the reminiscence per entry is decrease than a node per key. Consumer-defined keys want solely __hash__ and __eq__, and string hashing is randomized per course of except PYTHONHASHSEED is ready. The dict documentation covers the interface.
The customized ChainMap and OpenMap on this article exist to indicate the mechanics, to not compete with dict. They use hash() and == just like the built-in, return None for a lacking key, and don’t assist None values, as a result of None is the lacking marker. The identify ChainMap right here means separate chaining. It’s unrelated to collections.ChainMap, which teams a number of mappings into one view.
C#
public sealed class ChainMap<TKey, TValue>
the place TKey : notnull
{
non-public sealed class Node
{
public Node(TKey key, TValue worth)
{
Key = key;
Worth = worth;
}
public TKey Key { get; }
public TValue Worth { get; set; }
public Node? Subsequent { get; set; }
}
non-public static readonly EqualityComparer<TKey> s_comparer = EqualityComparer<TKey>.Default;
non-public Node?[] _buckets = new Node?[8];
non-public int _count;
/// <abstract>Stay entries within the map.</abstract>
public int Depend => _count;
/// <abstract>Bucket slots. Begins at 8 and doubles; all the time an influence of two.</abstract>
public int Capability => _buckets.Size;
/// <abstract>Inserts a brand new key or overwrites the worth of an present one.</abstract>
public void Put(TKey key, TValue worth)
{
ArgumentNullException.ThrowIfNull(key);
ArgumentNullException.ThrowIfNull(worth);
int bucket = Bucket(key);
for (Node? node = _buckets[bucket]; node will not be null; node = node.Subsequent)
{
if (s_comparer.Equals(node.Key, key))
{
node.Worth = worth; // an replace by no means grows the desk
return;
}
}
// Develop earlier than the brand new key goes in, by no means after: the demo's sizes and
// the capability it prints depend upon this order.
if (_count + 1 > (_buckets.Size * 3) / 4)
Develop();
bucket = Bucket(key);
_buckets[bucket] = new Node(key, worth) { Subsequent = _buckets[bucket] };
_count++;
}
/// <abstract>
/// Appears to be like up a key. Returns false when the hot button is lacking and leaves
/// <paramref identify="worth"/> at its default worth.
/// </abstract>
public bool TryGet(TKey key, out TValue worth)
{
ArgumentNullException.ThrowIfNull(key);
for (Node? node = _buckets[Bucket(key)]; node will not be null; node = node.Subsequent)
{
if (s_comparer.Equals(node.Key, key))
{
worth = node.Worth;
return true;
}
}
worth = default!;
return false;
}
/// <abstract>Removes a key. Returns false when the hot button is lacking.</abstract>
public bool Take away(TKey key)
{
ArgumentNullException.ThrowIfNull(key);
int bucket = Bucket(key);
Node? earlier = null;
for (Node? node = _buckets[bucket]; node will not be null; node = node.Subsequent)
{
if (s_comparer.Equals(node.Key, key))
{
if (earlier is null)
_buckets[bucket] = node.Subsequent;
else
earlier.Subsequent = node.Subsequent;
_count--;
return true;
}
earlier = node;
}
return false;
}
The C# chained class makes use of EqualityComparer<TKey>.Default for each hashing and equality, which is what the bottom class library does, and the open-addressed class retains the identical parallel arrays. The customized class follows the library’s TryGetValue sample with TryGet, which returns false and leaves the worth at its default when the hot button is lacking.
In utility code, use System.Collections.Generic.Dictionary<TKey,TValue>. It shops entries in a single array with a bucket index array and chains collisions by way of integer subsequent indices reasonably than pointers, which retains the entries compact. It resizes when the entry array fills. It’s not thread-safe, ConcurrentDictionary<TKey,TValue> is the shared-access model, and its enumeration order is unspecified.
The Load Issue and the Size of a Probe
A probe is one slot examined. For chaining it’s one node in contrast. For linear probing it’s one array slot learn. The 2 methods have closed-form expectations, and the experiment runs each on the similar 4 load components, with the identical 100,000 combined keys and the identical combined hash for integers, then averages the probes over each key and over 100,000 keys that aren’t current.
static bool measure_open(size_t capability, const uint32_t *keys,
double *hit, size_t *max_probe, double *miss)
{
uint32_t *slots = malloc(capability * sizeof *slots);
unsigned char *occupied = calloc(capability, 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)capability);
whereas (occupied[index])
index = (index + 1) % capability;
occupied[index] = 1;
slots[index] = keys[i];
}
double complete = 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)capability);
size_t probes = 0;
for (;;) {
probes++;
if (occupied[index] && slots[index] == keys[i])
break;
index = (index + 1) % capability;
}
complete += (double)probes;
if (probes > largest)
largest = probes;
}
*hit = complete / (double)KEY_COUNT;
*max_probe = largest;
rng_seed(SEED_MISS);
complete = 0.0;
size_t measured = 0;
whereas (measured < (size_t)MISS_COUNT) {
uint32_t key = next_key();
size_t index = (size_t)(mix32(key) % (uint32_t)capability);
size_t probes = 0;
bool discovered = false;
for (;;) {
probes++;
if (!occupied[index])
break;
if (slots[index] == key) {
discovered = true; /* absent key drawn by chance */
break;
}
index = (index + 1) % capability;
}
if (!discovered) {
complete += (double)probes;
measured++;
}
}
*miss = complete / (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
Three issues stand out within the output. The measured successful-lookup probes match the system at each load issue for chaining, inside 0.01, and for linear probing inside 0.01 as much as a load of 0.75 and inside 0.21 at 0.90. The formulation are expectations for a random hash, and the combined integer hash behaves like one.
The unsuccessful lookup is the place linear probing separates: 2.48 probes at load 0.50, 8.44 at 0.75 and 54.90 at 0.90, in opposition to the system’s 2.50, 8.50 and 50.49, whereas chaining’s miss value is its load issue, 0.50, 0.75 and 0.90. The longest probe sequence tells the identical story from the tail: 25 slots at 0.50, 120 at 0.75 and 794 at 0.90 for linear probing, in opposition to a longest chain of 6, 8 and seven for chaining.
A single lookup close to the load restrict can subsequently contact lots of of slots, which is why the tables on this article develop at 0.75 reasonably than at 0.95. The measured miss worth at 0.90 is 9% above the system, the one place the place the random-hash assumption is visibly stretched.
A Weak Hash and a Good Hash on the Similar Keys
A hash operate decides how the keys distribute earlier than any collision technique acts. Cryptographic hashing is a distinct job, lined by the MD5 and SHA article. A hash desk wants pace, a large output vary and good mixing for its key form. The experiment makes use of a set of fifty,000 keys formed like actual e-mail addresses, constructed from two fastened identify arrays so the set is equivalent on each run, and hashes them into 131,072 buckets with a chained desk. Three capabilities are in contrast: the primary byte solely, the sum of all bytes, and FNV-1a 32-bit, the variant laid out 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 != ' '; ++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 != ' '; ++p) {
hash ^= *p;
hash *= 16777619u;
}
return hash;
}
static bool run_hash(const char *label, HashFn hash,
char current[][MAX_KEY], char absent[][MAX_KEY])
{
int *heads = malloc(BUCKETS * sizeof *heads);
int *subsequent = malloc(KEY_COUNT * sizeof *subsequent);
if (heads == NULL || subsequent == NULL) {
free(heads);
free(subsequent);
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(current[i]) % (uint32_t)BUCKETS);
subsequent[i] = heads[bucket];
heads[bucket] = (int)i;
}
size_t longest = 0;
size_t non_empty = 0;
double comparisons = 0.0; /* each node is in contrast as soon as per chain place */
for (size_t i = 0; i < (size_t)BUCKETS; ++i) {
size_t size = 0;
for (int node = heads[i]; node >= 0; node = subsequent[node])
size++;
if (size > 0) {
non_empty++;
comparisons += (double)size * (double)(size + 1) / 2.0;
}
if (size > longest)
longest = size;
}
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 size = 0;
for (int node = heads[bucket]; node >= 0; node = subsequent[node])
size++;
miss_sum += (double)size;
}
double miss = miss_sum / (double)MISS_COUNT;
printf("%-12s %-9zu %-9.2f %-8.2f %.2fn",
label, longest, average_chain, hit, miss);
free(heads);
free(subsequent);
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 primary-byte hash fails as anticipated: each key that begins with the identical letter lands in a single bucket. The longest chain holds 7,034 keys, the typical 3,125, and a profitable lookup compares 2,039 keys on common, which is the behaviour of a linked checklist with further steps. Sum-of-bytes is best however nonetheless poor: a longest chain of 172, a median of 37.7 and 39.2 comparisons per hit, as a result of the byte sum has a slender vary and no place data.
FNV-1a retains the longest chain at 5, the typical at 1.20 and the hit at 1.19, and its miss value is 0.38 entries, concerning the 0.38 load issue. The worst and greatest longest chains differ by an element of 1,407, and their common hit prices by an element of 1,714. A hash that fails to make use of the entire key and blend it can’t be rescued by a greater collision technique.
A great hash solely protects in opposition to keys that arrive by probability. When an attacker can select the keys, as with HTTP parameters or JSON subject names despatched to a server, a hard and fast public hash similar to FNV-1a will be fed hundreds of keys that land in a single bucket, turning each lookup into a listing stroll. The FNV specification itself doesn’t suggest FNV the place an lively adversary is concerned.
The usual libraries defend in opposition to this in several methods: CPython and .NET randomize string hashes per course of, and Java’s HashMap can fall again on key order inside a crowded bucket when the keys are Comparable. A desk that hashes untrusted enter ought to depend on these defaults or use a keyed hash similar to SipHash.
Deleting From an Open-Addressing Desk
Deletion is the place the 2 methods diverge most. A chained desk unlinks a node and is finished. An open-addressing desk can’t clear the slot, as a result of a later lookup for a key that probed previous that slot would cease on the empty one and miss. The slot has to turn into a tombstone, and the lookup has to deal with a tombstone as “hold going” whereas remembering the primary tombstone as a spot a later insert could reuse.
static bool table_probe(const ChurnTable *desk, uint32_t key,
size_t *probes)
{
size_t index = (size_t)(mix32(key) % (uint32_t)table->capability);
for (size_t step = 0; step < table->capability; ++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->capability;
}
*probes = table->capability;
return false;
}
/* Inserts a key that's identified to be absent: the primary slot that isn't
* occupied, a tombstone or an empty slot, takes it. */
static bool table_put_new(ChurnTable *desk, uint32_t key)
{
size_t index = (size_t)(mix32(key) % (uint32_t)table->capability);
for (size_t step = 0; step < table->capability; ++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->stay++;
return true;
}
index = (index + 1) % table->capability;
}
return false;
}
/* Averages the probes of a profitable lookup of each stay key and of an
* unsuccessful lookup of ABSENT_KEYS keys that had been by no means inserted. */
static void table_measure(const ChurnTable *desk, double *hit, double *miss)
{
double complete = 0.0;
for (size_t i = 0; i < table->capability; ++i) {
if (table->states[i] != STATE_OCCUPIED)
proceed;
size_t probes = 0;
table_probe(desk, table->keys[i], &probes);
complete += (double)probes;
}
*hit = complete / (double)table->stay;
rng_seed(SEED_ABSENT);
complete = 0.0;
size_t measured = 0;
whereas (measured < (size_t)ABSENT_KEYS) {
uint32_t key = next_random();
if (history_contains(key))
proceed; /* a used key will not be an absent key */
size_t probes = 0;
if (table_probe(desk, key, &probes)) {
fprintf(stderr, "inner error: absent key's presentn");
exit(EXIT_FAILURE);
}
complete += (double)probes;
measured++;
}
*miss = complete / (double)ABSENT_KEYS;
}
Output:
open addressing, 131072 slots, linear probing
spherical stay tombstones hit miss
begin 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 price behind. After the preliminary fill the desk solutions a lacking key in 8.60 probes. After 4 delete-and-reinsert rounds it holds 24,262 tombstones and the identical lacking lookup prices 33.37 probes, 3.9 occasions extra, whereas the profitable lookup rises from 2.53 to three.75 probes, 48% extra. The stay rely by no means adjustments at 98,304, so the load issue stays at 0.75 and the system would predict a continuing 8.50. The tombstones are the entire distinction.
Rebuilding the desk from its stay entries drops the tombstones and returns the miss value to 9.05 probes, near the preliminary 8.60. A desk ought to rebuild when the tombstone rely turns into a big fraction of the capability, not solely when the stay rely crosses the expansion threshold.
The experiment’s desk intentionally by no means rebuilds, so the price stays seen. The open maps within the 5 repositories do rebuild: they rely tombstones as used slots, and when stay entries plus tombstones would move three quarters of the capability they rebuild on the similar dimension, which retains the miss value close to its beginning worth beneath any quantity of churn.
std::unordered_map with and and not using a Reserve
The usual libraries conceal these selections behind defaults that aren’t all the time those a program wants. The benchmark inserts 1,000,000 distinct int keys into 4 maps, appears to be like each key up, and studies the time and the bucket state. The heap is measured whereas the map holds all of the entries.
int important()
{
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 Consequence default_result =
median_run([&keys] { return run_std_once<Config::plain>(keys); });
const Consequence reserved_result =
median_run([&keys] { return run_std_once<Config::reserved>(keys); });
const Consequence low_load_result =
median_run([&keys] { return run_std_once<Config::load_half>(keys); });
const Consequence 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 throughout the 4 mapsn");
return EXIT_FAILURE;
}
std::printf("1,000,000 inserts + lookups, median of 5 runs (ms)n");
std::printf("%-31s%.1f buckets %zu load %.2fn",
"std::unordered_map, default", default_result.ms,
default_result.buckets, default_result.load);
std::printf("%-31s%.1f buckets %zu load %.2fn",
"std::unordered_map, reserved", reserved_result.ms,
reserved_result.buckets, reserved_result.load);
std::printf("%-31s%.1f buckets %zu load %.2fn",
"std::unordered_map, load 0.5", low_load_result.ms,
low_load_result.buckets, low_load_result.load);
std::printf("%-31s%.1f capability %zu max_probe %zun",
"customized open addressing", custom_result.ms,
custom_result.capability, custom_result.max_probe);
std::printf("heap whereas holding 1,000,000 entries (bytes)n");
std::printf("std::unordered_map %zun", default_heap);
std::printf("customized open addressing %zun", custom_heap);
std::printf("checksum: %llun",
static_cast<unsigned lengthy lengthy>(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
customized open addressing 268.5 capability 2097152 max_probe 190
heap whereas holding 1,000,000 entries (bytes)
std::unordered_map 43579088
customized 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 rising repeatedly from its preliminary bucket rely. Calling reserve(2'000'000), room for twice the ultimate entry rely, minimize the time to 287.4 ms and ended at 2,144,977 buckets at a load of 0.47. The reserve eliminated the expansion path totally. Reducing the load issue to 0.5 on prime of the reserve took 253.0 ms, an extra 12%, with 4,026,031 buckets at a load of 0.25.
The customized 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 entire run, inserts and rehashes included. It was 7% sooner than the reserved commonplace map and 6% slower than the low-load one, whereas utilizing 18,878,544 bytes in opposition to the usual map’s 43,579,088, 2.3 occasions much less heap. The 2 outcomes level in several instructions: the library map with a reserve is near the customized map in time, and the customized map’s compact arrays use lower than half its reminiscence.
5 Methods a Hash Desk Passes a Fast Take a look at and Nonetheless Fails
Every of those packages compiles cleanly with -Wall -Wextra -pedantic, and every prints one thing that appears believable till the road beneath it. The 4 C packages stay within the C repository’s pitfalls/ listing and the C++ one within the C++ repository’s. The workflows re-run every and assert the road that exhibits the bug.
1. Clearing the Slot on Delete
static void map_remove_clearing(ProbeMap *map, int key)
{
size_t index = slot_for(key);
whereas (map->states[index] == OCCUPIED) {
if (map->keys[index] == key) {
map->states[index] = EMPTY;
map->live--;
return;
}
index = (size_t)((index + 1) % (size_t)CAPACITY);
}
}
/* Appropriate probing: cease solely at a slot that was by no means occupied for the reason that final
* rehash. A cleared slot appears to be like the identical as one, which is the failure. */
static bool map_get(const ProbeMap *map, int key, int *out)
{
size_t index = slot_for(key);
whereas (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
take away 11 -> true
get 19 -> lacking, as a result of slot 4 is now empty
The map removes 11 by clearing slot 4. Slot 5 nonetheless holds 19, however get(19) hashes to fit 3, finds 3, then finds slot 4 empty and stops, so a key that’s within the desk is reported lacking. A tombstone at slot 4 would hold the probe alive, which is why the open map on this article marks removals as an alternative of clearing them.
2. A Desk 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->stay++;
return true;
}
index = (index + 1) % (size_t)CAPACITY;
}
return false; /* no empty slot left: "full" */
}
Output:
tombstone_full: inserts skip tombstones, so deletion house is misplaced
delete all 5 keys -> stay 0, tombstones 5, empty 3
insert 8, 9, 10 -> stay 3, tombstones 5, empty 0
insert 11 -> full true, stay 3, tombstones 5
The insert routine treats a tombstone as occupied, so after deleting 5 keys every insert walks previous the 5 tombstones and fills the three remaining empty slots. When these are used, the map studies full with three stay entries and 5 tombstones. An insert should keep in mind and reuse the primary tombstone on its probe path, as open_place does.
3. Inserting the Similar Key Twice
static bool map_put_buggy(ChainMap *map, const char *key, int worth)
{
if (map->used == (size_t)MAX_KEYS)
return false;
Node *node = &map->nodes[map->used++];
node->key = key;
node->worth = worth;
node->subsequent = NULL;
size_t bucket = bucket_for(key);
if (map->buckets[bucket] == NULL) {
map->buckets[bucket] = node;
} else {
Node *tail = map->buckets[bucket];
whereas (tail->subsequent != NULL)
tail = tail->subsequent;
tail->subsequent = node;
}
map->dimension++;
return true;
}
Output:
duplicate_key: chaining insert by no means checks for an present key
put alice 1 -> dimension 1, chain size 1
put alice 2 -> dimension 2, chain size 2
get alice -> 1, anticipated 2
The buggy put appends a node with out checking the chain, so alice is saved twice: dimension 2, chain size 2, and get reads the older worth 1 whereas the caller anticipated 2. Each hash map should search earlier than it inserts. The price of that search is a part of why the desk retains its load issue low.
4. Rehashing With out Remapping
static bool map_grow_stale(ChainMap *map)
{
size_t new_capacity = map->capability * 2;
Node **buckets = calloc(new_capacity, sizeof *buckets);
if (buckets == NULL)
return false;
for (size_t i = 0; i < map->capability; ++i) {
Node *node = map->buckets[i];
whereas (node != NULL) {
Node *subsequent = node->subsequent;
node->subsequent = buckets[i]; /* stale: must be new hash slot */
buckets[i] = node;
node = subsequent;
}
}
free(map->buckets);
map->buckets = buckets;
map->capability = new_capacity;
return true;
}
Output:
stale_rehash: progress retains every key at its previous bucket index
develop from 4 to eight buckets -> dimension 4, capability 8
get 10 -> 10
get 30 -> lacking, although it's saved in previous bucket 2
Development allocates eight buckets however copies every node to its previous bucket index. Key 10 nonetheless hashes to bucket 2 beneath each capacities and is discovered, however key 30 was in previous bucket 2 and belongs in bucket 6 beneath the brand new capability, so it’s reported lacking although its node is within the desk. Each rehash should recompute hash(key) % new_capacity.
5. Wanting Up With std::unordered_map::operator[]
// operator_index.cpp - DO NOT COPY. std::unordered_map::operator[] on a lacking
// key value-initializes the mapped worth and inserts the important thing, so a learn that
// appears to be like like a lookup adjustments the scale of the map. Use discover() or at() as an alternative.
// Construct: g++ -std=c++17 -Wall -Wextra -pedantic pitfalls/operator_index.cpp -o operator_index
#embody <cstddef>
#embody <iostream>
#embody <string>
#embody <unordered_map>
int important()
{
std::unordered_map<std::string, int> word_counts;
word_counts["alice"] = 1;
std::cout << "operator_index: operator[] on a lacking keyn";
std::cout << "dimension earlier than the lookup: " << word_counts.dimension() << 'n';
std::cout << "rely for frank by way of operator[]: " << word_counts["frank"]
<< 'n';
std::cout << "dimension after the lookup: " << word_counts.dimension() << 'n';
}
Output:
operator_index: operator[] on a lacking key
dimension earlier than the lookup: 1
rely for frank by way of operator[]: 0
dimension after the lookup: 2
Studying a lacking key by way of operator[] inserts a default worth: the scale goes from 1 to 2 and the reported rely for frank is 0. Use discover(), comprises() in C++20, or at() for a learn. discover returns finish() with out inserting something, and at() throws std::out_of_range.
Key Takeaways
- A hash desk provides common O(1) insert, lookup and delete solely whereas the hash spreads keys and the load issue stays low. Each circumstances are measured right here.
- Linear probing tracks the textbook successful-lookup system however its unsuccessful lookup value climbs from 2.48 probes at load 0.50 to 54.90 at 0.90, whereas chaining misses value solely the load issue.
- A weak hash fails earlier than the collision technique will get an opportunity: on 50,000 email-shaped keys the first-byte hash reached a longest chain of seven,034, in opposition to 5 for FNV-1a.
- Deletion in an open-addressing desk wants a tombstone, and tombstones lengthen later lookups till the desk is rebuilt, and counting them towards the load issue triggers that rebuild routinely.
- A reproduction insert should replace the present worth, and a rehash should recompute every key’s bucket within the new desk.
std::unordered_mapresizes at a defaultmax_load_factorof 1.0, and areservename minimize the benchmark from 539.9 ms to 287.4 ms.- A hard and fast public hash similar to FNV-1a is open to hash flooding when attackers select the keys. Servers ought to depend on randomized or keyed hashing.
Incessantly Requested Questions
Conclusion
The hash desk is the construction whose worst case is determined earlier than any code runs. A hash that makes use of the entire key and mixes it, a load issue that stays beneath its progress threshold, and a tombstone rule that retains probe chains intact are the three selections that hold insert, lookup and delete at common O(1). Every of them appeared right here as a measured quantity: probe counts in opposition to the textbook formulation, a series size of seven,034 in opposition to 5 on the identical keys, and a missing-key lookup that grew 3.9 occasions beneath tombstone churn earlier than a rebuild restored it.
In manufacturing code, use the library: std::unordered_map with a reserve, HashMap in Java, dict in Python and Dictionary<TKey,TValue> in C#, and attain for the hand-written variations when the probing or the reminiscence format needs to be managed. The information buildings hub lists the buildings that construct on this one.
Supply Code and Exams
All packages on this web page are within the data-structures/hash-table listing of the 5 MYCPLUS instance repositories:
The C and C++ examples construct and take a look at with CMake:
cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
Java runs with javac --release 17 -Xlint:all -Werror -d construct src/*.java exams/*.java adopted by java -ea -cp construct MapTest; Python with python -m unittest uncover -s exams -v; C# with dotnet construct HashTable.slnx -c Launch adopted by dotnet run --project exams/MapTests -c Launch --no-build.
What the builds test. Each demo’s stdout is in contrast byte for byte with the information in exams/anticipated/. The exams examine each maps in opposition to the usual library map over 100,000 random operations, together with duplicate updates, lacking keys, removals of absent keys, tombstone churn and at the very least 5 resizes, they usually test that each worth put and never eliminated is discovered. The C and C++ workflows additionally run the exams and demos beneath AddressSanitizer and UndefinedBehaviorSanitizer, and the C workflow re-runs the 4 pitfalls and checks the road every prints. The builds don’t test the probe figures, the hash-quality figures or the timings: these belong to 1 machine and are captured with the article.
What I Verified
The instance directories comprise the take a look at packages and the captured runs. The desk states which system ran every test.
| Verify | Ubuntu 24.04 (WSL2) | Home windows 11 (MSVC) |
|---|---|---|
| Construct and exams, C, GCC 13.3 | Cross (8 of 8 exams) | Not relevant |
| Construct and exams, C, Clang 18.1.3 | Cross (8 of 8 exams) | Not relevant |
Construct and exams, C, MSVC 19.44 /W4 /WX |
Not relevant | Cross (8 of 8 exams) |
| Construct and exams, C++, g++ 13.3 | Cross (5 of 5 exams) | Not relevant |
| Construct and exams, C++, clang++ 18.1.3 | Cross (5 of 5 exams) | Not relevant |
Construct and exams, C++, MSVC 19.44 /W4 /WX /permissive- |
Not relevant | Cross (4 of 4 exams; the benchmark is Linux solely) |
| Java exams, JDK 21 on Ubuntu and JDK 27 on Home windows | Cross (all exams, two demo diffs) | Cross (all exams, two demo diffs) |
Python exams (3.12.3 on Ubuntu, 3.14.6 on Home windows), ruff and mypy --strict |
Cross (24 exams, two demo diffs, ruff and mypy clear) | Cross (all exams, two demo diffs, ruff and mypy clear) |
| .NET construct and exams (SDK 10.0.115 on Ubuntu, 10.0.404 on Home windows) | Cross (all exams, two demo diffs) | Cross (all exams, two demo diffs) |
| AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ exams and demos | Cross (C 8 of 8, C++ 5 of 5) | Not relevant |
| 5 pitfalls, every caught by the test named in its part | Cross (4 C checks, 1 C++ test) | Not relevant |
| Probe, hash-quality, tombstone and benchmark experiments | Run on Ubuntu 24.04, figures within the sections above | Not run |
Not lined: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 domestically (the CI matrix covers them), macOS, and timings on some other machine.

