What Is a Hashtable?
A hashtable is a data construct that stores a set of items. Each item has a key that identifies the item. Items are found, added, and removed from the hashtable by using the key. Hashtables may seem like arrays, but there are important differences:
|Keys:||integer: arrays are always keyed on integers, and must be contiguous.||any type: almost any datatype can be used as key, including strings, integers, XPCOM interface pointers, IIDs, and almost anything else. Keys can be disjunct (i.e. you can store entries with keys 1, 5, and 3000).|
|Lookup Time:||O(1): lookup time is a simple constant||O(1): lookup time is mostly-constant, but the constant time can be larger than an array lookup|
|Sorting:||sorted: stored sorted; enumerated in a sorted fashion.||unsorted: stored unsorted; cannot be enumerated in a sorted manner.|
|Inserting/Removing:||O(n): adding and removing items from a large array can be time-consuming||O(1): adding and removing items from hashtables is a quick operation|
|Wasted space:||none: Arrays are packed structures, so there is no wasted space.||some: hashtables are not packed structures; depending on on the implementation, there may be significant wasted memory.|
In their implementation, hashtables take the key and apply a mathematical hash function to “randomize�? the key and then use the hash to find the location in the hashtable. Good hashtable implementations will automatically resize the hashtable in memory if extra space is needed, or if too much space has been allocated.
When Should I Use a Hashtable?
Mozilla's Hashtable Implementations
Which Hashtable Should I Use?
nsBaseHashtable and friends: nsDataHashtable, nsInterfaceHashtable, and nsClassHashtable
Mozilla's Old/Obsolete/Deprecated/Decrepit Hashtables
Original Document Information
- Author(s): Benjamin Smedberg <firstname.lastname@example.org>