Skip to content
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

=OrderedSet.filter Attempt to optimize filter impl #163

Merged
merged 3 commits into from
Aug 18, 2022
Merged
Show file tree
Hide file tree
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
19 changes: 19 additions & 0 deletions Benchmarks/Benchmarks/OrderedSetBenchmarks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,25 @@ extension Benchmark {
}
}

for percent in [0, 25, 50, 75, 100] {
self.add(
title: "OrderedSet<Int> filter keeping \(percent)%",
input: [Int].self
) { input in
let set = OrderedSet(input)
return { timer in
var r: OrderedSet<Int>!
timer.measure {
r = set.filter { $0 % 100 < percent }
}
let div = input.count / 100
let rem = input.count % 100
precondition(r.count == percent * div + Swift.min(rem, percent))
blackHole(r)
}
}
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like your benchmark suite a lot btw, very nice work 👍


let overlaps: [(String, (Int) -> Int)] = [
("0%", { c in c }),
("25%", { c in 3 * c / 4 }),
Expand Down
14 changes: 8 additions & 6 deletions Sources/OrderedCollections/OrderedSet/OrderedSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -508,13 +508,15 @@ extension OrderedSet {
/// - Complexity: O(`count`)
@inlinable
public func filter(
_ isIncluded: (Element) throws -> Bool
_ isIncluded: (Element) throws -> Bool
) rethrows -> Self {
var result: OrderedSet = Self(minimumCapacity: _minimumCapacity)
for element in self where try isIncluded(element) {
result._appendNew(element)
try _UnsafeBitset.withTemporaryBitset(capacity: self.count) { bitset in
for i in _elements.indices where try isIncluded(_elements[i]) {
bitset.insert(i)
}
let result = self._extractSubset(using: bitset)
result._checkInvariants()
return result
}
result._checkInvariants()
return result
}
}