How does Dictionary<TKey,TValue> handle hash collisions internally, and why does a poor GetHashCode() implementation degrade its performance?
Short answer
Dictionary uses a hash table with SEPARATE CHAINING (or a similar bucket-based collision resolution) — when multiple keys hash to the same bucket, it falls back to a linear scan WITHIN that bucket using Equals(); a poorly-distributed GetHashCode() (e.g., one that always returns…
Advertisement
AModel answer
Dictionary<TKey,TValue> uses a hash table with SEPARATE CHAINING (or a similar bucket-based collision resolution) — when multiple keys hash to the same bucket, it falls back to a linear scan WITHIN that bucket using Equals(); a poorly-distributed GetHashCode() (e.g., one that always returns the same value) collapses the theoretical O(1) average lookup into effectively O(n), since every key lands in the same bucket.
public class BadKey {
public override int GetHashCode() => 1; // terrible: every instance collides into the same bucket
}
// A Dictionary<BadKey, T> degrades to O(n) linear-scan performanceReal-world example
Debugging a mysteriously slow Dictionary-based cache traced back to a custom key type with a poorly-implemented GetHashCode().
Likely follow-ups
- What's the contractual relationship that GetHashCode() and Equals() must maintain for a custom key type to work correctly?
Related topics