summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorBenjamin Lee <benjamindlee@me.com>2020-10-06 04:29:45 -0400
committerGitHub <noreply@github.com>2020-10-06 10:29:45 +0200
commitacd71dd6bb745eb08f81ab489d635951f8edfcfa (patch)
treebe453e981adffc79f1d0abd92df0c5100630b841
parentaca1fae55a8009627888944afeb69f0a0141c160 (diff)
downloadNim-acd71dd6bb745eb08f81ab489d635951f8edfcfa.tar.gz
Iterate over smaller set when computing intersection (#15497)
Closes #15496
-rw-r--r--lib/pure/collections/sets.nim11
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`.