Skip to content

Commit ed9ad60

Browse files
authored
change intersect order to reduce time (#36339)
1 parent 26d2e19 commit ed9ad60

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

base/abstractset.jl

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,14 @@ Set{Float64} with 1 element:
146146
```
147147
"""
148148
function intersect(s::AbstractSet, itr, itrs...)
149+
# heuristics to try to `intersect` with the shortest Set on the left
150+
if length(s)>50 && haslength(itr) && all(haslength, itrs)
151+
min_length, min_idx = findmin(length, itrs)
152+
if length(itr) > min_length
153+
new_itrs = setindex(itrs, itr, min_idx)
154+
return intersect(s, itrs[min_idx], new_itrs...)
155+
end
156+
end
149157
T = promote_eltype(s, itr, itrs...)
150158
if T == promote_eltype(s, itr)
151159
out = intersect(s, itr)
@@ -156,7 +164,13 @@ function intersect(s::AbstractSet, itr, itrs...)
156164
return intersect!(out, itrs...)
157165
end
158166
intersect(s) = union(s)
159-
intersect(s::AbstractSet, itr) = mapfilter(in(s), push!, itr, emptymutable(s, promote_eltype(s, itr)))
167+
function intersect(s::AbstractSet, itr)
168+
if haslength(itr) && hasfastin(itr) && length(s) < length(itr)
169+
return mapfilter(in(itr), push!, s, emptymutable(s, promote_eltype(s, itr)))
170+
else
171+
return mapfilter(in(s), push!, itr, emptymutable(s, promote_eltype(s, itr)))
172+
end
173+
end
160174

161175
const = intersect
162176

test/sets.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,9 @@ end
242242
s = S([1,2]) S([3,4])
243243
@test s == S()
244244
s = intersect(S([5,6,7,8]), S([7,8,9]))
245+
slong = S(collect(3:63))
246+
# test #36339 length/order short-cut
247+
@test intersect(S([5,6,7,8]), slong) == intersect(slong, S([5,6,7,8]))
245248
@test s == S([7,8])
246249
@test intersect(S([2,3,1]), S([4,2,3]), S([5,4,3,2])) == S([2,3])
247250
let s1 = S([1,2,3])

0 commit comments

Comments
 (0)