File tree Expand file tree Collapse file tree 1 file changed +21
-4
lines changed Expand file tree Collapse file tree 1 file changed +21
-4
lines changed Original file line number Diff line number Diff line change @@ -561,13 +561,30 @@ public struct Set<Element : Hashable> :
561
561
public func intersect<
562
562
S : SequenceType where S.Generator.Element == Element
563
563
>(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.
565
567
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)
569
585
}
570
586
}
587
+
571
588
return newSet
572
589
}
573
590
You can’t perform that action at this time.
0 commit comments