Mastering data structures in Ruby — Sets
Ale Miralles
52

Thanks for the article (and the linked lists one), I’m enjoying this series.

I may have found a more efficient way of implementing Set#union. Instead of inserting each element of self into the resultant Set, why not just #dup or #clone it before inserting the elements of other?

There may be very good reasons for not doing this but I don’t really know enough about #dup or #clone to know what they are.

My benchmarks show #dup to be slightly faster than #clone and both to be ~2.5x faster than a double insert for uniting equal size Sets. The gains increase considerably with a relatively larger receiver.

I’m showing benchmarks using #dup only — #clone gave similar gains.

Equal size sets:

Larger receiver:

I would love to hear your thoughts and I’m looking forward to the next instalment.