diff options
author | Benjamin Lee <benjamindlee@me.com> | 2020-10-06 04:29:45 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-10-06 10:29:45 +0200 |
commit | acd71dd6bb745eb08f81ab489d635951f8edfcfa (patch) | |
tree | be453e981adffc79f1d0abd92df0c5100630b841 | |
parent | aca1fae55a8009627888944afeb69f0a0141c160 (diff) | |
download | Nim-acd71dd6bb745eb08f81ab489d635951f8edfcfa.tar.gz |
Iterate over smaller set when computing intersection (#15497)
Closes #15496
-rw-r--r-- | lib/pure/collections/sets.nim | 11 |
1 files changed, 9 insertions, 2 deletions
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index 67e407576..98dedc5ff 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -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`. |