Ruby symbols: hash keys
This course measures the speed difference between Ruby symbols and strings and explains where it comes from. It uses the standard Benchmark module to time symbol and string equality, then hash lookups with symbol and string keys. A logging class shows how Hash calls #hash and #eql? to find a key. The course then shows that most of the measured gap comes from string literals allocating new objects, covers Hash#compare_by_identity, and builds a counting hash with symbol keys and Hash.new(0).
What you'll learn
- ✓Timing code with Benchmark.bm and reading its user, system, total and real columns
- ✓Comparing symbol and string speed for equality checks and hash lookups
- ✓How Hash uses #hash to pick a bucket and #eql? to confirm a key
- ✓Why string literal allocation explains most of the gap, and how frozen string literals change it
- ✓Using Hash#compare_by_identity to compare keys by object identity
- ✓Counting occurrences into a symbol-keyed hash with Hash.new(0)
This isn't folklore anymore
The intern course Ruby symbols vs strings already did real work here. Its lesson "Memory efficiency and comparison speed" explained that symbols are interned. :admin written anywhere in a program is always the same object, while "admin" written twice usually creates two separate String objects. A…
Read the full lesson free →Curriculum
7 lessonsThis isn't folklore anymore
Recaps why symbols are interned and lays out a plan to measure their speed with Benchmark.
Benchmarking symbol vs string equality
Uses Benchmark.bm to show string equality running about three times slower, partly from allocating new strings.
Benchmarking hash lookup: where it matters
Measures hash reads, where symbol keys ran about twice as fast as string keys over 5 million lookups.
How Hash finds your key
A logging class shows Hash calling #hash then #eql?, and frozen string literals nearly erase the gap.
Hash#compare_by_identity: forcing identity comparison
Shows how Hash#compare_by_identity makes two strings with equal content count as two separate keys.
Counting and grouping with symbol keys
Builds a counts hash keyed by symbols in a loop, then shortens it with Hash.new(0).
Putting it together: from claim to proof
Reviews the measurements and the #hash and #eql? mechanism, then sets an exercise to write a counting method.