Skip to content

Commit

Permalink
RFC: Iterate over smaller set for setdiff[!](a,b) (#29048)
Browse files Browse the repository at this point in the history
* Iterate over smaller set for setdiff[!]

* Add comment and change to integer multiplication

(cherry picked from commit 773540d)
  • Loading branch information
laborg authored and KristofferC committed Feb 11, 2019
1 parent 9e156b2 commit f7c68c5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
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

0 comments on commit f7c68c5

Please sign in to comment.