Skip to content

Commit 6f8bee1

Browse files
committed
Merge pull request #576 from dduan/set_intersect_optimization
[Performance] iterate the smaller set during Set.intersect()
2 parents 3653e22 + d919f4c commit 6f8bee1

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

stdlib/public/core/HashedCollections.swift.gyb

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -561,13 +561,30 @@ public struct Set<Element : Hashable> :
561561
public func intersect<
562562
S : SequenceType where S.Generator.Element == Element
563563
>(sequence: S) -> Set<Element> {
564-
let other = sequence as? Set<Element> ?? Set(sequence)
564+
565+
// Attempt to iterate the smaller between `self` and `sequence`.
566+
// If sequence is not a set, iterate over it because it may be single-pass.
565567
var newSet = Set<Element>()
566-
for member in self {
567-
if other.contains(member) {
568-
newSet.insert(member)
568+
569+
if let other = sequence as? Set<Element> {
570+
let smaller: Set<Element>
571+
let bigger: Set<Element>
572+
if other.count > count {
573+
smaller = self
574+
bigger = other
575+
} else {
576+
smaller = other
577+
bigger = self
578+
}
579+
for element in smaller where bigger.contains(element) {
580+
newSet.insert(element)
581+
}
582+
} else {
583+
for element in sequence where contains(element) {
584+
newSet.insert(element)
569585
}
570586
}
587+
571588
return newSet
572589
}
573590

0 commit comments

Comments
 (0)