Skip to content

Commit 4e0c6f9

Browse files
authored
[stdlib] Set.intersection iterate over smaller set (#36678)
* [stdlib] Set.intersection iterate over smaller set When intersecting two sets, it is beneficial to iterate over the smaller sized set of the two, and check membership on the other. This speeds up runtime dramatically for cases where the current set is significantly larger than the set you are intersecting against. * Review comments - variable names, implicit swap
1 parent 553d441 commit 4e0c6f9

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

stdlib/public/core/Set.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1223,8 +1223,10 @@ extension Set {
12231223
@inlinable
12241224
public __consuming func intersection(_ other: Set<Element>) -> Set<Element> {
12251225
var newSet = Set<Element>()
1226-
for member in self {
1227-
if other.contains(member) {
1226+
let (smaller, larger) =
1227+
count < other.count ? (self, other) : (other, self)
1228+
for member in smaller {
1229+
if larger.contains(member) {
12281230
newSet.insert(member)
12291231
}
12301232
}

0 commit comments

Comments
 (0)