Iterate over smaller set when computing intersection (#15497)

Closes #15496
This commit is contained in:
Benjamin Lee
2020-10-06 04:29:45 -04:00
committed by GitHub
parent aca1fae55a
commit acd71dd6bb

View File

@@ -422,8 +422,15 @@ proc intersection*[A](s1, s2: HashSet[A]): HashSet[A] =
assert c == toHashSet(["b"])
result = initHashSet[A](max(min(s1.data.len, s2.data.len), 2))
for item in s1:
if item in s2: incl(result, item)
# iterate over the elements of the smaller set
if s1.data.len < s2.data.len:
for item in s1:
if item in s2: incl(result, item)
else:
for item in s2:
if item in s1: incl(result, item)
proc difference*[A](s1, s2: HashSet[A]): HashSet[A] =
## Returns the difference of the sets `s1` and `s2`.