Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Iterate over smaller set for setdiff[!](a,b) #29048

Merged
merged 2 commits into from
Sep 11, 2018
Merged
Show file tree
Hide file tree
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
20 changes: 20 additions & 0 deletions base/set.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,26 @@ rehash!(s::Set) = (rehash!(s.dict); s)

iterate(s::Set, i...) = iterate(KeySet(s.dict), i...)

# In case the size(s) is smaller than size(t) its more efficient to iterate through
# elements of s instead and only delete the ones also contained in t.
# The threshold for this decision boils down to a tradeoff between
# size(s) * cost(in() + delete!()) ≶ size(t) * cost(delete!())
# Empirical observations on Ints point towards a threshold of 0.8.
# To be on the safe side (e.g. cost(in) >>> cost(delete!) ) a
# conservative threshold of 0.5 was chosen.
function setdiff!(s::Set, t::Set)
if 2 * length(s) < length(t)
for x in s
x in t && delete!(s, x)
end
else
for x in t
delete!(s, x)
end
end
return s
end

"""
unique(itr)

Expand Down
8 changes: 8 additions & 0 deletions test/sets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,14 @@ end
s = Set([1,2,3,4])
setdiff!(s, Set([2,4,5,6]))
@test isequal(s,Set([1,3]))

# setdiff iterates the shorter set - make sure this algorithm works
sa, sb = Set([1,2,3,4,5,6,7]), Set([2,3,9])
@test Set([1,4,5,6,7]) == setdiff(sa, sb) !== sa
@test Set([1,4,5,6,7]) == setdiff!(sa, sb) === sa
sa, sb = Set([1,2,3,4,5,6,7]), Set([2,3,9])
@test Set([9]) == setdiff(sb, sa) !== sb
@test Set([9]) == setdiff!(sb, sa) === sb
end

@testset "ordering" begin
Expand Down