Stop memoizing Hash lookups in Ruby
When a method performs a slow operation, memoizing the result using instance variables is a useful optimization. However, I’ve often seen people (including myself, sometimes!) reaching for memoization for things that don’t need to be optimized.
One common example is when there’s a class that wraps a Hash object. Hashes in Ruby are quite well optimized, so do you really need to memoize the result of the hash lookup? Let’s benchmark and find out.
Benchmarks
Let’s start with a simple Setting
class that takes a data hash with type
and value
keys.
class Setting
def initialize(data)
@data = data
end
def type
@data["type"]
end
def type_memoized
@type ||= @data["type"]
…
There’s a type
method here, and I’ve added a type_memoized
method for comparison.
Now let’s…