Archive for February 15, 2018
-
Ruby performance: Hash's #has_key? vs. #[] (square brackets)
February 15, 2018
During my time last year developing performance improvements for Rambling Trie, I stumbled into something quite interesting that happens with Ruby’s
Hash
class.A commonly used method from the
Hash
interface is#has_key?
which tells you if theHash
in question contains a particular key. Rambling Trie’s underlying data structure is an n-ary tree backed by aHash
where each key is the letter corresponding to a child and each value is theNode
that corresponds to that letter. As you might imagine,#has_key?
is a common operation called throughout the gem implementation.To my surprise, while running some Ruby benchmarks I noticed that accessing the key with
#[]
and verifying if it wasnil
instead of calling#has_key?
lowered the time it took…