Merge pull request #433 from apple/dn-optimize-unspecialized-performance

Optimize unspecialized `OrderedSet.init` and `OrderedSet.firstIndex(of:)`
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2024-11-21 16:31:49 -08:00
commit 1e6a561203
3 files changed
+107 -8

No files matched your search

@@ -292,11 +292,20 @@ extension _HashTable.UnsafeHandle {
extension _UnsafeHashTable {
@inlinable
internal func _find<Base: RandomAccessCollection>(
_ item: Base.Element,
in elements: Base
) -> (index: Int?, bucket: Bucket)
where Base.Element: Hashable {
internal func _find<Element: Hashable>(
_ item: Element,
in elements: ContiguousArray<Element>
) -> (index: Int?, bucket: Bucket) {
elements.withUnsafeBufferPointer { buffer in
_find(item, in: buffer)
}
}
@inlinable
internal func _find<Element: Hashable>(
_ item: Element,
in elements: UnsafeBufferPointer<Element>
) -> (index: Int?, bucket: Bucket) {
let start = idealBucket(for: item)
var (iterator, value) = startFind(start)
while let index = value {
@@ -502,6 +511,24 @@ extension _UnsafeHashTable {
) where C.Element: Hashable {
assertMutable()
assert(elements.count <= capacity)
// fast path that doesn't allocate per element if _read accessor can't
// be inlined because this function doesn't get specialized e.g.
// if `Element` isn't known at compile time.
let fastPath: Void? = elements.withContiguousStorageIfAvailable { elements in
// Iterate over elements and insert their offset into the hash table.
var offset = 0
for index in elements.indices {
// Find the insertion position. We know that we're inserting a new item,
// so there is no need to compare it with any of the existing ones.
var it = bucketIterator(for: elements[index])
it.advanceToNextUnoccupiedBucket()
it.currentValue = offset
offset += 1
}
}
if fastPath != nil {
return
}
// Iterate over elements and insert their offset into the hash table.
var offset = 0
for index in elements.indices {
@@ -527,6 +554,30 @@ extension _UnsafeHashTable {
assertMutable()
assert(elements.count <= capacity)
// Iterate over elements and insert their offset into the hash table.
// fast path that doesn't allocate per element if _read accessor can't
// be inlined because this function doesn't get specialized e.g.
// if `Element` isn't known at compile time.
let fastPath: (success: Bool, end: Int)? = elements.withContiguousStorageIfAvailable { elements in
var offset = 0
for index in elements.indices {
// Find the insertion position. We know that we're inserting a new item,
// so there is no need to compare it with any of the existing ones.
var it = bucketIterator(for: elements[index])
while let offset = it.currentValue {
guard elements[_offset: offset] != elements[index] else {
return (false, index)
}
it.advance()
}
it.currentValue = offset
offset += 1
}
return (true, elements.endIndex)
}
if let fastPath {
return (fastPath.success, elements.index(elements.startIndex, offsetBy: fastPath.end))
}
var offset = 0
for index in elements.indices {
// Find the insertion position. We know that we're inserting a new item,
@@ -99,14 +99,31 @@ extension _HashTable {
let minScale = Self.scale(forCapacity: elements.count)
let scale = Swift.max(Swift.max(scale ?? 0, minScale),
reservedScale)
if scale < Self.minimumScale {
// Don't hash anything.
if elements.count < 2 { return (nil, elements.endIndex) }
var temp: [C.Element] = []
// fast path that doesn't allocate per element if _read accessor can't
// be inlined because this function doesn't get specialized e.g.
// if `Element` isn't known at compile time.
let firstDuplicateIndexFastPath: Int? = elements.withContiguousStorageIfAvailable { elements in
var temp: ContiguousArray<C.Element> = []
temp.reserveCapacity(elements.count)
for i in elements.indices {
let item = elements[i]
guard !temp._contains(item) else { return i }
temp.append(item)
}
return elements.endIndex
}
if let firstDuplicateIndexFastPath {
return (nil, elements.index(elements.startIndex, offsetBy: firstDuplicateIndexFastPath))
}
var temp: ContiguousArray<C.Element> = []
temp.reserveCapacity(elements.count)
for i in elements.indices {
let item = elements[i]
guard !temp.contains(item) else { return (nil, i) }
guard !temp._contains(item) else { return (nil, i) }
temp.append(item)
}
return (nil, elements.endIndex)
@@ -136,6 +153,21 @@ extension _HashTable {
}
}
/// copy of the standard library implementation of `Sequence.contains(_:)`
/// to allow partial specialization if `Element` is not known at compile time.
/// also some modification to remove some more generic overhead.
extension ContiguousArray where Element: Equatable {
@inlinable
func _contains(_ element: Element) -> Bool {
for index in 0..<count {
if element == self[index] {
return true
}
}
return false
}
}
extension _HashTable {
@@ -433,7 +433,7 @@ extension OrderedSet {
internal func _find_inlined(_ item: Element) -> (index: Int?, bucket: _Bucket) {
_elements.withUnsafeBufferPointer { elements in
guard let table = _table else {
return (elements.firstIndex(of: item), _Bucket(offset: 0))
return (elements._firstIndex(of: item), _Bucket(offset: 0))
}
return table.read { hashTable in
hashTable._find(item, in: elements)
@@ -481,6 +481,22 @@ extension OrderedSet {
}
}
/// copy of the standard library implementation of `Collection.firstIndex(of:)`
/// to allow partial specialization if `Element` is not known at compile time
extension UnsafeBufferPointer where Element: Equatable {
@inlinable
func _firstIndex(of element: Element) -> Index? {
var i = self.startIndex
while i != self.endIndex {
if self[i] == element {
return i
}
self.formIndex(after: &i)
}
return nil
}
}
extension OrderedSet {
@inlinable
@inline(never)