Benchmarking #include? for Ruby Array, Set, and Hash
which has faster #inlude? check
What data structure is better to use when you need to check whether an item is in a collection?
I wrote a benchmark for a predictable outsider — Array, for not so widely known Set, and for Hash a favorite of the audience.
The benchmark has results for Hash#[]
method, which is interesting to compare with Hash#include?
.
With a collection of 58 items Set outperforms Array about 2 times and Hash about 3.5 times faster than Array.
With a larger collection of 504 items, the difference becomes more obvious. Set outperforms Array about 11,5 times and Hash faster than Array about 15 times.
No surprise that Hash and Set results is close. Set uses Hash as storage for its values. Hash and Set have one more advantage over Array, they don’t store same value more than once.
The benchmark made with Ruby version 2.5.1.
Bellow code of the benchmark that I encourage you to run yourself.
I also include bechmark results for Ruby 2.6.0.
Feedback is welcome.