Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions lib/set.rb
Original file line number Diff line number Diff line change
Expand Up @@ -361,16 +361,15 @@ def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end

def flatten_merge(set, seen = Set.new) # :nodoc:
def flatten_merge(set, seen = Set.new.compare_by_identity) # :nodoc:
set.each { |e|
if e.is_a?(Set)
if seen.include?(e_id = e.object_id)
unless seen.add?(e)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's 3 nice performance wins here:

  • We don't trigger a look up (and potentially an assignment) of an object ID
  • We can do an identity-based look-up, which is faster
  • We combine the include? and add steps into one, saving one hash lookup/comparison.

raise ArgumentError, "tried to flatten recursive Set"
end

seen.add(e_id)
flatten_merge(e, seen)
seen.delete(e_id)
seen.delete(e)
else
add(e)
end
Expand Down