Skip to content

Commit b1f77b2

Browse files
authored
[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.
1 parent 0b31642 commit b1f77b2

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

stdlib/public/core/Set.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1223,7 +1223,11 @@ extension Set {
12231223
@inlinable
12241224
public __consuming func intersection(_ other: Set<Element>) -> Set<Element> {
12251225
var newSet = Set<Element>()
1226-
for member in self {
1226+
var (iter, other) = (self, other)
1227+
if iter.count > other.count {
1228+
swap(&iter, &other)
1229+
}
1230+
for member in iter {
12271231
if other.contains(member) {
12281232
newSet.insert(member)
12291233
}

0 commit comments

Comments
 (0)