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
Hashclass.A commonly used method from the
Hashinterface is#has_key?which tells you if theHashin question contains a particular key. Rambling Trie’s underlying data structure is an n-ary tree backed by aHashwhere each key is the letter corresponding to a child and each value is theNodethat 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 wasnilinstead of calling#has_key?lowered the time it took…