Ruby Set#include? vs bitwise & benchmark
I was reviewing some code recently which included Set#include?
. I was curious about the
performance implications of Set#include?
vs Enumerable#include?
which can be MUCH slower than
say a bitwise &
and wanted to test it out.
Benchmark
As you can see Set#include?
is quite fast. The reason is Set
maintains a hash object
representing the Set
. It checks against it for inclusion, making the operation
constant.
irb(main):014:0> Set.new([1,2,3,4]).instance_variable_get('@hash')
=> {1=>true, 2=>true, 3=>true, 4=>true}