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
commit acd71dd6bb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

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