Skip to content

[Performance] iterate the smaller set during Set.intersect() #576

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 20, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions stdlib/public/core/HashedCollections.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -561,13 +561,30 @@ public struct Set<Element : Hashable> :
public func intersect<
S : SequenceType where S.Generator.Element == Element
>(sequence: S) -> Set<Element> {
let other = sequence as? Set<Element> ?? Set(sequence)

// Attempt to iterate the smaller between `self` and `sequence`.
// If sequence is not a set, iterate over it because it may be single-pass.
var newSet = Set<Element>()
for member in self {
if other.contains(member) {
newSet.insert(member)

if let other = sequence as? Set<Element> {
let smaller: Set<Element>
let bigger: Set<Element>
if other.count > count {
smaller = self
bigger = other
} else {
smaller = other
bigger = self
}
for element in smaller where bigger.contains(element) {
newSet.insert(element)
}
} else {
for element in sequence where contains(element) {
newSet.insert(element)
}
}

return newSet
}

Expand Down