HashMap

Intro

A hash map stores key-value pairs and uses hashing to find a bucket quickly. The goal is fast insert, lookup, and delete by key — O(1) average, O(n) worst case when all keys collide into one bucket. In .NET, the primary hash map implementation is Dictionary<TKey, TValue>, while Hashtable is the older non-generic version. A concrete example: a user session cache storing 50K active sessions by session ID achieves sub-microsecond lookups with Dictionary<string, Session>, where the same lookup in a List<Session> would scan 25K entries on average.

Deeper Explanation

Hash maps use two rules together: hash distribution and equality checks.

Structure

graph TD
    K1[key user one] --> H1[hash to bucket one]
    K2[key user two] --> H2[hash to bucket three]
    H1 --> E1[user one value ann]
    H2 --> E2[user two value bob]

Example

var usersById = new Dictionary<int, string>
{
    [1001] = "Ann",
    [1002] = "Bob"
};

if (usersById.TryGetValue(1002, out var name))
{
    Console.WriteLine(name);
}

Pitfalls

Tradeoffs

Questions

Hash-Based Collections Comparison

Type Key type Thread-safe When to use
Dictionary<TKey,TValue> Generic No Default hash map in modern .NET
Hashtable object No Legacy interop only
HashSet<T> N/A (values only) No Unique value membership
ConcurrentDictionary<TKey,TValue> Generic Yes Concurrent read/write

Decision rule: use Dictionary<TKey,TValue> by default. Hashtable only for legacy API compatibility.


Whats next