Skip to content

IndexSet.union performance improvement #28325

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
Nov 18, 2019
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
23 changes: 15 additions & 8 deletions stdlib/public/Darwin/Foundation/IndexSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -442,16 +442,23 @@ public struct IndexSet : ReferenceConvertible, Equatable, BidirectionalCollectio

/// Union the `IndexSet` with `other`.
public func union(_ other: IndexSet) -> IndexSet {
// This algorithm is naïve but it works. We could avoid calling insert in some cases.

var result = IndexSet()
for r in self.rangeView {
result.insert(integersIn: r)
var result: IndexSet
var dense: IndexSet

// Prepare to make a copy of the more sparse IndexSet to prefer copy over repeated inserts
if self.rangeView.count > other.rangeView.count {
result = self
dense = other
} else {
result = other
dense = self
}

for r in other.rangeView {
result.insert(integersIn: r)

// Insert each range from the less sparse IndexSet
dense.rangeView.forEach {
result.insert(integersIn: $0)
}

return result
}

Expand Down