Why are symbols often preferred over strings as hash keys?
Last updated
Symbols are preferred as hash keys because they are immutable and interned: the same symbol is one shared object, so it hashes consistently and compares quickly, making lookups fast and memory-efficient.
Single shared object:
:idused as a key everywhere is the same object, while"id"string keys could allocate many objects.Immutable and stable hash: A key's
hashmust not change. Symbols can't be mutated; a mutable string key could be altered and "lost" in the hash.Faster comparison: Resolving collisions compares keys via identity for symbols rather than char-by-char for strings.
Idiomatic: Ruby/Rails conventions (keyword args, options hashes) use symbol keys;
{ name: "Ann" }is symbol-keyed sugar.Note: String literal keys are auto-frozen when
# frozen_string_literal: trueis on, narrowing the gap, but symbols remain clearer and conventional.