Junior Track Roadmap

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)
Free preview · Lesson 1 2 min read

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 lessons
Type to start searching...