This isn't folklore anymore

Free preview 2 min to read

What two earlier lessons established

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 symbol's equality check can lean on that shared object, closer to "are these the same object" than "do these have the same characters". Its lesson "When to use symbols: hash keys and identifiers" turned that into a rule. Data (something read, stored or edited) leans String. A label (a fixed identifier, known in advance, that a program checks against) leans Symbol, and hash keys are the most common case of a label.

Neither lesson measured anything. One of that course's takeaways called the differences "real and mechanical, not folklore", mattering most at scale. This course puts numbers on that claim. The numbers turn out more interesting than "symbols are faster".

From claim to evidence

"Symbols are faster" is easy to repeat and easy to get wrong, exaggerated in one direction and dismissed in the other. Ruby's standard library has a tool for checking: Benchmark, no gem required, built for timing code and comparing results. The next two lessons use it on symbol and string operations running on this app's Ruby 4.0.1, instead of numbers copied from somewhere else.

What comes after the numbers

A measured speed difference answers "how much", not "why". Once the next two lessons have numbers, lesson 4 opens the mechanism Hash uses to find a key: #hash and #eql?, methods every Ruby object already has. That's where the explanation lives, along with a surprise about what the benchmarks were measuring.

Key takeaways

  • Ruby symbols vs strings already covered why symbols are interned and when to choose one over a string as a hash key; neither is repeated here.
  • One of that course's takeaways called the performance difference real, not folklore; this course measures it.
  • Ruby's standard Benchmark module times running code with no gem needed, and the next two lessons use it.
  • The plan: measure equality, measure hash lookup, then open the #hash/#eql? mechanism behind both numbers.
Lesson 1 of 7 · free

Keep going with lesson 2

Benchmarking symbol vs string equality

Uses Benchmark.bm to show string equality running about three times slower, partly from allocating new strings.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...