HOME

TheInfoList



OR:

Cuckoo hashing is a scheme in
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
for resolving
hash collision In computer science, a hash collision or hash clash is when two distinct pieces of data in a hash table share the same hash value. The hash value in this case is derived from a hash function which takes a data input and returns a fixed length of ...
s of values of
hash function A hash function is any Function (mathematics), function that can be used to map data (computing), data of arbitrary size to fixed-size values, though there are some hash functions that support variable-length output. The values returned by a ...
s in a
table Table may refer to: * Table (database), how the table data arrangement is used within the databases * Table (furniture), a piece of furniture with a flat surface and one or more legs * Table (information), a data arrangement with rows and column ...
, with worst-case constant lookup time. The name derives from the behavior of some species of
cuckoo Cuckoos are birds in the Cuculidae ( ) family, the sole taxon in the order Cuculiformes ( ). The cuckoo family includes the common or European cuckoo, roadrunners, koels, malkohas, couas, coucals, and anis. The coucals and anis are somet ...
, where the cuckoo chick pushes the other eggs or young out of the nest when it hatches in a variation of the behavior referred to as
brood parasitism Brood parasitism is a subclass of parasitism and phenomenon and behavioural pattern of animals that rely on others to raise their young. The strategy appears among birds, insects and fish. The brood parasite manipulates a host, either of the ...
; analogously, inserting a new key into a cuckoo hashing table may push an older key to a different location in the table.


History

Cuckoo hashing was first described by Rasmus Pagh and Flemming Friche Rodler in a 2001 conference paper. The paper was awarded the
European Symposium on Algorithms The European Symposium on Algorithms (ESA) is an international conference covering the field of algorithms. It has been held annually since 1993, typically in early Autumn in a different European location each year. Like most theoretical computer ...
Test-of-Time award in 2020.


Operations

Cuckoo hashing is a form of
open addressing Open addressing, or closed hashing, is a method of Hash table#Collision resolution, collision resolution in hash tables. With this method a hash collision is resolved by probing, or searching through alternative locations in the array (the ''prob ...
in which each non-empty cell of a
hash table In computer science, a hash table is a data structure that implements an associative array, also called a dictionary or simply map; an associative array is an abstract data type that maps Unique key, keys to Value (computer science), values. ...
contains a key or key–value pair. A
hash function A hash function is any Function (mathematics), function that can be used to map data (computing), data of arbitrary size to fixed-size values, though there are some hash functions that support variable-length output. The values returned by a ...
is used to determine the location for each key, and its presence in the table (or the value associated with it) can be found by examining that cell of the table. However, open addressing suffers from collisions, which happens when more than one key is mapped to the same cell. The basic idea of cuckoo hashing is to resolve collisions by using two hash functions instead of only one. This provides two possible locations in the hash table for each key. In one of the commonly used variants of the algorithm, the hash table is split into two smaller tables of equal size, and each hash function provides an index into one of these two tables. It is also possible for both hash functions to provide indexes into a single table.


Lookup

Cuckoo hashing uses two hash tables, T_1 and T_2. Assuming r is the length of each table, the hash functions for the two tables is defined as, h_1,\ h_2\ :\ S \rightarrow \ and \forall x \in S where x is the key and S is the set whose keys are stored in h_1(x) of T_1 or h_2(x) of T_2. The lookup operation is as follows: The
logical or In logic, disjunction (also known as logical disjunction, logical or, logical addition, or inclusive disjunction) is a logical connective typically notated as \lor and read aloud as "or". For instance, the English language, English language ...
(\vee) denotes that, the value of the key x is found in either T_1 or T_2, which is O(1) in worst case.


Deletion

Deletion is performed in O(1) time since probing is not involved. This ignores the cost of the shrinking operation if the table is too sparse.


Insertion

When inserting a new item with key x, the first step involves examining if slot h_1(x) of table T_1 is occupied. If it is not, the item is inserted in that slot. However, if the slot is occupied, the existing item x' is removed and x is inserted at T_1 _1(x)/math>. Then, x' is inserted into table T_2 by following the same procedure. The process continues until an empty position is found to insert the key. To avoid an
infinite loop In computer programming, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs, such as turning off power via a switch or pulling a plug. It may be inte ...
, a threshold \text is specified. If the number of iterations exceeds this fixed threshold, both T_1 and T_2 are rehashed with new hash functions and the insertion procedure repeats. The following is
pseudocode In computer science, pseudocode is a description of the steps in an algorithm using a mix of conventions of programming languages (like assignment operator, conditional operator, loop) with informal, usually self-explanatory, notation of actio ...
for insertion: On lines 10 and 15, the "cuckoo approach" of kicking other keys which occupy T_ _(x)/math> repeats until every key has its own "nest", i.e. item x is inserted into an empty slot in either of the two tables. The notation x\leftrightarrow y expresses swapping x and y.


Theory

Insertions succeed in expected constant time, even considering the possibility of having to rebuild the table, as long as the number of keys is kept below half of the capacity of the hash table, i.e., the load factor is below 50%. One method of proving this uses the theory of
random graph In mathematics, random graph is the general term to refer to probability distributions over graphs. Random graphs may be described simply by a probability distribution, or by a random process which generates them. The theory of random graphs l ...
s: one may form an
undirected graph In discrete mathematics, particularly in graph theory, a graph is a structure consisting of a set of objects where some pairs of the objects are in some sense "related". The objects are represented by abstractions called '' vertices'' (also call ...
called the "cuckoo graph" that has a vertex for each hash table location, and an edge for each hashed value, with the endpoints of the edge being the two possible locations of the value. Then, the greedy insertion algorithm for adding a set of values to a cuckoo hash table succeeds if and only if the cuckoo graph for this set of values is a
pseudoforest In graph theory, a pseudoforest is an undirected graphThe kind of undirected graph considered here is often called a multigraph or pseudograph, to distinguish it from a simple graph. in which every Connected component (graph theory), connected com ...
, a graph with at most one cycle in each of its connected components. Any vertex-induced subgraph with more edges than vertices corresponds to a set of keys for which there are an insufficient number of slots in the hash table. When the hash function is chosen randomly, the cuckoo graph is a
random graph In mathematics, random graph is the general term to refer to probability distributions over graphs. Random graphs may be described simply by a probability distribution, or by a random process which generates them. The theory of random graphs l ...
in the
Erdős–Rényi model In the mathematical field of graph theory, the Erdős–Rényi model refers to one of two closely related models for generating random graphs or the evolution of a random network. These models are named after Hungarians, Hungarian mathematicians ...
. With high probability, for load factor less than 1/2 (corresponding to a random graph in which the ratio of the number of edges to the number of vertices is bounded below 1/2), the graph is a pseudoforest and the cuckoo hashing algorithm succeeds in placing all keys. The same theory also proves that the expected size of a connected component of the cuckoo graph is small, ensuring that each insertion takes constant expected time. However, also with high probability, a load factor greater than 1/2 will lead to a giant component with two or more cycles, causing the data structure to fail and need to be resized. Since a theoretical random hash function requires too much space for practical usage, an important theoretical question is which practical hash functions suffice for Cuckoo hashing. One approach is to use k-independent hashing. In 2009 it was shown that O(\log n)-independence suffices, and at least 6-independence is needed. Another approach is to use
tabulation hashing A table is an arrangement of information or data, typically in rows and columns, or possibly in a more complex structure. Tables are widely used in communication, research, and data analysis. Tables appear in print media, handwritten notes, comp ...
, which is not 6-independent, but was shown in 2012 to have other properties sufficient for Cuckoo hashing. A third approach from 2014 is to slightly modify the cuckoo hashtable with a so-called stash, which makes it possible to use nothing more than 2-independent hash functions.


Practice

In practice, cuckoo hashing is about 20–30% slower than
linear probing Linear probing is a scheme in computer programming for resolving hash collision, collisions in hash tables, data structures for maintaining a collection of Attribute–value pair, key–value pairs and looking up the value associated with a giv ...
, which is the fastest of the common approaches. The reason is that cuckoo hashing often causes two cache misses per search, to check the two locations where a key might be stored, while linear probing usually causes only one cache miss per search. However, because of its worst case guarantees on search time, cuckoo hashing can still be valuable when real-time response rates are required.


Example

The following hash functions are given (the two least significant digits of k in base 11): h\left(k\right)=k\bmod 11
h'\left(k\right)=\left\lfloor\frac\right\rfloor\bmod 11 The following two tables show the insertion of some example elements. Each column corresponds to the state of the two hash tables over time. The possible insertion locations for each new value are highlighted. The last column illustrates a failed insertion due to a cycle, details below.


Cycle

If you attempt to insert the element 45, then you get into a cycle, and fail. In the last row of the table we find the same initial situation as at the beginning again. h\left(45\right)=45\bmod 11=1
h'\left(45\right)=\left\lfloor\frac\right\rfloor\bmod 11=4


Variations

Several variations of cuckoo hashing have been studied, primarily with the aim of improving its space usage by increasing the load factor that it can tolerate to a number greater than the 50% threshold of the basic algorithm. Some of these methods can also be used to reduce the failure rate of cuckoo hashing, causing rebuilds of the data structure to be much less frequent. Generalizations of cuckoo hashing that use more than two alternative hash functions can be expected to utilize a larger part of the capacity of the hash table efficiently while sacrificing some lookup and insertion speed. Using just three hash functions increases the load to 91%. Another generalization of cuckoo hashing called ''blocked cuckoo hashing'' uses more than one key per bucket and a balanced allocation scheme. Using just 2 keys per bucket permits a load factor above 80%. Another variation of cuckoo hashing that has been studied is ''cuckoo hashing with a stash''. The stash, in this data structure, is an array of a constant number of keys, used to store keys that cannot successfully be inserted into the main hash table of the structure. This modification reduces the failure rate of cuckoo hashing to an inverse-polynomial function with an exponent that can be made arbitrarily large by increasing the stash size. However, larger stashes also mean slower searches for keys that are not present or are in the stash. A stash can be used in combination with more than two hash functions or with blocked cuckoo hashing to achieve both high load factors and small failure rates. The analysis of cuckoo hashing with a stash extends to practical hash functions, not just to the random hash function model commonly used in theoretical analysis of hashing. Some people recommend a simplified generalization of cuckoo hashing called skewed-associative cache in some
CPU cache A CPU cache is a hardware cache used by the central processing unit (CPU) of a computer to reduce the average cost (time or energy) to access data from the main memory. A cache is a smaller, faster memory, located closer to a processor core, whi ...
s. Another variation of a cuckoo hash table, called a cuckoo filter, replaces the stored keys of a cuckoo hash table with much shorter fingerprints, computed by applying another hash function to the keys. In order to allow these fingerprints to be moved around within the cuckoo filter, without knowing the keys that they came from, the two locations of each fingerprint may be computed from each other by a bitwise
exclusive or Exclusive or, exclusive disjunction, exclusive alternation, logical non-equivalence, or logical inequality is a logical operator whose negation is the logical biconditional. With two inputs, XOR is true if and only if the inputs differ (on ...
operation with the fingerprint, or with a hash of the fingerprint. This data structure forms an approximate set membership data structure with much the same properties as a
Bloom filter In computing, a Bloom filter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives ar ...
: it can store the members of a set of keys, and test whether a query key is a member, with some chance of
false positive A false positive is an error in binary classification in which a test result incorrectly indicates the presence of a condition (such as a disease when the disease is not present), while a false negative is the opposite error, where the test resu ...
s (queries that are incorrectly reported as being part of the set) but no false negatives. However, it improves on a Bloom filter in multiple respects: its memory usage is smaller by a constant factor, it has better
locality of reference In computer science, locality of reference, also known as the principle of locality, is the tendency of a processor to access the same set of memory locations repetitively over a short period of time. There are two basic types of reference localit ...
, and (unlike Bloom filters) it allows for fast deletion of set elements with no additional storage penalty.


Comparison with related structures

A study by Zukowski et al. has shown that cuckoo hashing is much faster than chained hashing for small, cache-resident hash tables on modern processors. Kenneth Ross has shown bucketized versions of cuckoo hashing (variants that use buckets that contain more than one key) to be faster than conventional methods also for large hash tables, when space utilization is high. The performance of the bucketized cuckoo hash table was investigated further by Askitis, with its performance compared against alternative hashing schemes. A survey by Mitzenmacher presents open problems related to cuckoo hashing as of 2009.


Known users

Cuckoo hashing is used in
TikTok TikTok, known in mainland China and Hong Kong as Douyin (), is a social media and Short-form content, short-form online video platform owned by Chinese Internet company ByteDance. It hosts user-submitted videos, which may range in duration f ...
's recommendation system to solve the problem of "embedding table collisions", which can result in reduced model quality. The TikTok recommendation system "Monolith" takes advantage cuckoo hashing's collision resolution to prevent different concepts from being mapped to the same vectors.


See also

* Perfect hashing *
Double hashing Double hashing is a computer programming technique used in conjunction with open addressing in hash tables to resolve hash collisions, by using a secondary hash of the key as an offset when a collision occurs. Double hashing with open addressing is ...
*
Quadratic probing Quadratic probing is an open addressing scheme in computer programming for resolving hash collisions in hash tables. Quadratic probing operates by taking the original hash index and adding successive values of an arbitrary quadratic polynomial un ...
*
Hopscotch hashing Hopscotch hashing is a scheme in computer programming for resolving hash collisions of values of hash functions in a hash table, table using open addressing. It is also well suited for implementing a concurrent hash table. Hopscotch hashing was in ...


References


External links


A cool and practical alternative to traditional hash tables
, U. Erlingsson, M. Manasse, F. Mcsherry, 2006.
Cuckoo Hashing for Undergraduates, 2006
R. Pagh, 2006.

(Part 1

an

, Michael Mitzenmacher, 2007. * {{cite conference , last=Naor , first=Moni , author2=Segev, Gil , author3=Wieder, Udi , title=History-Independent Cuckoo Hashing , book-title=International Colloquium on Automata, Languages and Programming (ICALP) , place=Reykjavik, Iceland , year=2008 , url=http://www.wisdom.weizmann.ac.il/~naor/PAPERS/cuckoo_hi_abs.html , access-date=2008-07-21
Algorithmic Improvements for Fast Concurrent Cuckoo Hashing
X. Li, D. Andersen, M. Kaminsky, M. Freedman. EuroSys 2014.


Examples


Concurrent high-performance Cuckoo hashtable written in C++

Cuckoo hash map written in C++





Cuckoo hashing for Go
Search algorithms Hashing pl:Tablica mieszająca#Haszowanie kuku.C5.82cze