Merge pull request #702 from apple/dn/bit-set-count

Improve `BitSet.count` performance by ~3x
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2026-08-18 13:54:33 -07:00
commit f425dffd5b
2 files changed
+24 -2

No files matched your search

@@ -83,6 +83,28 @@ extension Benchmark {
}
}
self.add(
title: "BitSet count",
input: Int.self
) { input in
guard input > 0 else { return nil }
var set = BitSet(reservingCapacity: input)
var expected = 0
for i in 0 ..< input where i.isMultiple(of: 3) {
set.insert(i)
expected += 1
}
// Make sure the set actually fills its storage capacity.
if set.insert(input - 1).inserted {
expected += 1
}
return { timer in
let c = set.count
precondition(c == expected)
blackHole(c)
}
}
self.add(
title: "BitSet distance(from:to:)",
input: Int.self
@@ -274,9 +274,9 @@ extension _UnsafeBitSet: Sequence {
extension _UnsafeBitSet: BidirectionalCollection {
@inlinable
@inline(__always)
package var count: Int {
_words.reduce(0) { $0 + $1.count }
assert(_words.count <= Int.max / _Word.capacity)
return _words.reduce(0) { $0 &+ $1.count }
}
@inlinable