mirror of
https://github.com/apple/swift-collections
synced 2026-11-24 04:27:53 +00:00
* [Heap] Don't always inline large functions
* [docs] Use a stable link to the Atkinson article
(The original link was pointing to course materials at a random university.)
* Remove stray import
* Revert "[Heap] Don't always inline large functions"
This reverts commit 07ffd6591f.
* [Heap] Enable code coverage collection in Xcode scheme
* [Heap] Speed up invariant checking
* [Heap] Precalculate levels for each offset
`_Node` is a new struct that consists of a storage offset (the old index) along with its level in the tree. The level can be incrementally calculated, saving some time vs counting bits whenever it's needed.
* [Heap] Switch to using unsafe buffer pointers
Introduce `Heap._UnsafeHandle` (a thin wrapper around an unsafe buffer pointer) and rebase most heap algorithms on top of that instead of array operations.
This simplifies things by reducing (hopefully) unnecessary index validation, resulting in some measurable performance improvements.
* [Heap] Stop force-inlining bubbleUp; mark it releasenone
Not inlining such a large function speeds things up by leaving some headroom for the optimizer to make better inlining decisions elsewhere. (Force inlining this resulted in the compiler not inlining the closure passed to `_update` instead, which isn't a great tradeoff.
To speed things up, mark `bubbleUp` with `@_effects(releasenone)`. This may be questionable (because it calls `Element.<`), but it results in better codegen, making `insert` match the performance of `std::priority_queue`.
* [Heap] Rework removals
* [Heap] Remove dead code
* [Heap] Switch to using _ContiguousArray as storage
* [Heap] insert<S>(contentsOf:): add fast path for count == 0 case
* [Heap] Perf pass on trickleDown code paths
This improves popMin/popMax (and the sequence initializer) by reviewing trickleDown and optimizing things:
- Replace swapAt with a scheme where we keep a hold in the storage buffer
- Slightly shorten min/max dependency chain in primary sink loop
In exchange, we get even less readable code.
* [Heap] bubbleUp: remove @_effects attribute
This reintroduces retain/release operations for the empty array until https://github.com/apple/swift/pull/38898 lands.
Mitigate the performance costs of this by refactoring code to reduce the size of the inlined bubbleUpMin/Max invocations.
* [Heap] Finetune Heap.insert
372 lines
11 KiB
Swift
372 lines
11 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift Collections open source project
|
|
//
|
|
// Copyright (c) 2021 Apple Inc. and the Swift project authors
|
|
// Licensed under Apache License v2.0 with Runtime Library Exception
|
|
//
|
|
// See https://swift.org/LICENSE.txt for license information
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
extension Heap {
|
|
@usableFromInline @frozen
|
|
struct _UnsafeHandle {
|
|
@usableFromInline
|
|
var buffer: UnsafeMutableBufferPointer<Element>
|
|
|
|
@inlinable @inline(__always)
|
|
init(_ buffer: UnsafeMutableBufferPointer<Element>) {
|
|
self.buffer = buffer
|
|
}
|
|
}
|
|
|
|
@inlinable @inline(__always)
|
|
mutating func _update<R>(_ body: (_UnsafeHandle) -> R) -> R {
|
|
_storage.withUnsafeMutableBufferPointer { buffer in
|
|
body(_UnsafeHandle(buffer))
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Heap._UnsafeHandle {
|
|
@inlinable @inline(__always)
|
|
internal var count: Int {
|
|
buffer.count
|
|
}
|
|
|
|
@inlinable
|
|
subscript(node: _Node) -> Element {
|
|
@inline(__always)
|
|
get {
|
|
buffer[node.offset]
|
|
}
|
|
@inline(__always)
|
|
nonmutating _modify {
|
|
yield &buffer[node.offset]
|
|
}
|
|
}
|
|
|
|
@inlinable @inline(__always)
|
|
internal func ptr(to node: _Node) -> UnsafeMutablePointer<Element> {
|
|
assert(node.offset < count)
|
|
return buffer.baseAddress! + node.offset
|
|
}
|
|
|
|
/// Move the value at the specified node out of the buffer, leaving it
|
|
/// uninitialized.
|
|
@inlinable @inline(__always)
|
|
internal func extract(_ node: _Node) -> Element {
|
|
ptr(to: node).move()
|
|
}
|
|
|
|
@inlinable @inline(__always)
|
|
internal func initialize(_ node: _Node, to value: __owned Element) {
|
|
ptr(to: node).initialize(to: value)
|
|
}
|
|
|
|
/// Swaps the elements in the heap at the given indices.
|
|
@inlinable @inline(__always)
|
|
internal func swapAt(_ i: _Node, _ j: _Node) {
|
|
buffer.swapAt(i.offset, j.offset)
|
|
}
|
|
|
|
/// Swaps the element at the given node with the supplied value.
|
|
@inlinable @inline(__always)
|
|
internal func swapAt(_ i: _Node, with value: inout Element) {
|
|
let p = buffer.baseAddress.unsafelyUnwrapped + i.offset
|
|
swap(&p.pointee, &value)
|
|
}
|
|
|
|
|
|
@inlinable @inline(__always)
|
|
internal func minValue(_ a: _Node, _ b: _Node) -> _Node {
|
|
self[a] < self[b] ? a : b
|
|
}
|
|
|
|
@inlinable @inline(__always)
|
|
internal func maxValue(_ a: _Node, _ b: _Node) -> _Node {
|
|
self[a] < self[b] ? b : a
|
|
}
|
|
}
|
|
|
|
extension Heap._UnsafeHandle {
|
|
@inlinable
|
|
internal func bubbleUp(_ node: _Node) {
|
|
guard !node.isRoot else { return }
|
|
|
|
let parent = node.parent()
|
|
|
|
var node = node
|
|
if (node.isMinLevel && self[node] > self[parent])
|
|
|| (!node.isMinLevel && self[node] < self[parent]){
|
|
swapAt(node, parent)
|
|
node = parent
|
|
}
|
|
|
|
if node.isMinLevel {
|
|
while let grandparent = node.grandParent(),
|
|
self[node] < self[grandparent] {
|
|
swapAt(node, grandparent)
|
|
node = grandparent
|
|
}
|
|
} else {
|
|
while let grandparent = node.grandParent(),
|
|
self[node] > self[grandparent] {
|
|
swapAt(node, grandparent)
|
|
node = grandparent
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Heap._UnsafeHandle {
|
|
/// Sink the item at `node` to its correct position in the heap.
|
|
/// The given node must be minimum-ordered.
|
|
@inlinable
|
|
internal func trickleDownMin(_ node: _Node) {
|
|
assert(node.isMinLevel)
|
|
var node = node
|
|
var value = extract(node)
|
|
_trickleDownMin(node: &node, value: &value)
|
|
initialize(node, to: value)
|
|
}
|
|
|
|
@inlinable @inline(__always)
|
|
internal func _trickleDownMin(node: inout _Node, value: inout Element) {
|
|
// Note: `_Node` is quite the useless abstraction here, as we don't need
|
|
// to look at its `level` property, and we need to move sideways amongst
|
|
// siblings/cousins in the tree, for which we don't have direct operations.
|
|
// Luckily, all the `_Node` business gets optimized away, so this only
|
|
// affects the readability of the code, not its performance.
|
|
// The alternative would be to reintroduce offset-based parent/child
|
|
// navigation methods, which seems less palatable.
|
|
|
|
var gc0 = node.firstGrandchild()
|
|
while gc0.offset &+ 3 < count {
|
|
// Invariant: buffer slot at `node` is uninitialized
|
|
|
|
// We have four grandchildren, so we don't need to compare children.
|
|
let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
|
|
let minA = minValue(gc0, gc1)
|
|
|
|
let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
|
|
let gc3 = _Node(offset: gc0.offset &+ 3, level: gc0.level)
|
|
let minB = minValue(gc2, gc3)
|
|
|
|
let min = minValue(minA, minB)
|
|
guard self[min] < value else {
|
|
return // We're done -- `node` is a good place for `value`.
|
|
}
|
|
|
|
initialize(node, to: extract(min))
|
|
node = min
|
|
gc0 = node.firstGrandchild()
|
|
|
|
let parent = min.parent()
|
|
if self[parent] < value {
|
|
swapAt(parent, with: &value)
|
|
}
|
|
}
|
|
|
|
// At this point, we don't have a full complement of grandchildren, but
|
|
// we haven't finished sinking the item.
|
|
|
|
let c0 = node.leftChild()
|
|
if c0.offset >= count {
|
|
return // No more descendants to consider.
|
|
}
|
|
let min = _minDescendant(c0: c0, gc0: gc0)
|
|
guard self[min] < value else {
|
|
return // We're done.
|
|
}
|
|
|
|
initialize(node, to: extract(min))
|
|
node = min
|
|
|
|
if min < gc0 { return }
|
|
|
|
// If `min` was a grandchild, check the parent.
|
|
let parent = min.parent()
|
|
if self[parent] < value {
|
|
initialize(node, to: extract(parent))
|
|
node = parent
|
|
}
|
|
}
|
|
|
|
/// Returns the node holding the minimal item amongst the children &
|
|
/// grandchildren of a node in the tree. The parent node is not specified;
|
|
/// instead, this function takes the nodes corresponding to its first child
|
|
/// (`c0`) and first grandchild (`gc0`).
|
|
///
|
|
/// There must be at least one child, but there must not be a full complement
|
|
/// of 4 grandchildren. (Other cases are handled directly above.)
|
|
///
|
|
/// This method is an implementation detail of `trickleDownMin`. Do not call
|
|
/// it directly.
|
|
@inlinable
|
|
internal func _minDescendant(c0: _Node, gc0: _Node) -> _Node {
|
|
assert(c0.offset < count)
|
|
assert(gc0.offset + 3 >= count)
|
|
|
|
if gc0.offset < count {
|
|
if gc0.offset &+ 2 < count {
|
|
// We have three grandchildren. We don't need to compare direct children.
|
|
let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
|
|
let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
|
|
return minValue(minValue(gc0, gc1), gc2)
|
|
}
|
|
|
|
let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
|
|
let m = minValue(c1, gc0)
|
|
if gc0.offset &+ 1 < count {
|
|
// Two grandchildren.
|
|
let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
|
|
return minValue(m, gc1)
|
|
}
|
|
|
|
// One grandchild.
|
|
return m
|
|
}
|
|
|
|
let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
|
|
if c1.offset < count {
|
|
return minValue(c0, c1)
|
|
}
|
|
|
|
return c0
|
|
}
|
|
|
|
/// Sink the item at `node` to its correct position in the heap.
|
|
/// The given node must be maximum-ordered.
|
|
@inlinable
|
|
internal func trickleDownMax(_ node: _Node) {
|
|
assert(!node.isMinLevel)
|
|
var node = node
|
|
var value = extract(node)
|
|
|
|
_trickleDownMax(node: &node, value: &value)
|
|
initialize(node, to: value)
|
|
}
|
|
|
|
@inlinable @inline(__always)
|
|
internal func _trickleDownMax(node: inout _Node, value: inout Element) {
|
|
// See note on `_Node` in `_trickleDownMin` above.
|
|
|
|
var gc0 = node.firstGrandchild()
|
|
while gc0.offset &+ 3 < count {
|
|
// Invariant: buffer slot at `node` is uninitialized
|
|
|
|
// We have four grandchildren, so we don't need to compare children.
|
|
let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
|
|
let maxA = maxValue(gc0, gc1)
|
|
|
|
let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
|
|
let gc3 = _Node(offset: gc0.offset &+ 3, level: gc0.level)
|
|
let maxB = maxValue(gc2, gc3)
|
|
|
|
let max = maxValue(maxA, maxB)
|
|
guard value < self[max] else {
|
|
return // We're done -- `node` is a good place for `value`.
|
|
}
|
|
|
|
initialize(node, to: extract(max))
|
|
node = max
|
|
gc0 = node.firstGrandchild()
|
|
|
|
let parent = max.parent()
|
|
if value < self[parent] {
|
|
swapAt(parent, with: &value)
|
|
}
|
|
}
|
|
|
|
// At this point, we don't have a full complement of grandchildren, but
|
|
// we haven't finished sinking the item.
|
|
|
|
let c0 = node.leftChild()
|
|
if c0.offset >= count {
|
|
return // No more descendants to consider.
|
|
}
|
|
let max = _maxDescendant(c0: c0, gc0: gc0)
|
|
guard value < self[max] else {
|
|
return // We're done.
|
|
}
|
|
|
|
initialize(node, to: extract(max))
|
|
node = max
|
|
|
|
if max < gc0 { return }
|
|
|
|
// If `max` was a grandchild, check the parent.
|
|
let parent = max.parent()
|
|
if value < self[parent] {
|
|
initialize(node, to: extract(parent))
|
|
node = parent
|
|
}
|
|
}
|
|
|
|
/// Returns the node holding the maximal item amongst the children &
|
|
/// grandchildren of a node in the tree. The parent node is not specified;
|
|
/// instead, this function takes the nodes corresponding to its first child
|
|
/// (`c0`) and first grandchild (`gc0`).
|
|
///
|
|
/// There must be at least one child, but there must not be a full complement
|
|
/// of 4 grandchildren. (Other cases are handled directly above.)
|
|
///
|
|
/// This method is an implementation detail of `trickleDownMax`. Do not call
|
|
/// it directly.
|
|
@inlinable
|
|
internal func _maxDescendant(c0: _Node, gc0: _Node) -> _Node {
|
|
assert(c0.offset < count)
|
|
assert(gc0.offset + 3 >= count)
|
|
|
|
if gc0.offset < count {
|
|
if gc0.offset &+ 2 < count {
|
|
// We have three grandchildren. We don't need to compare direct children.
|
|
let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
|
|
let gc2 = _Node(offset: gc0.offset &+ 2, level: gc0.level)
|
|
return maxValue(maxValue(gc0, gc1), gc2)
|
|
}
|
|
|
|
let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
|
|
let m = maxValue(c1, gc0)
|
|
if gc0.offset &+ 1 < count {
|
|
// Two grandchildren.
|
|
let gc1 = _Node(offset: gc0.offset &+ 1, level: gc0.level)
|
|
return maxValue(m, gc1)
|
|
}
|
|
|
|
// One grandchild.
|
|
return m
|
|
}
|
|
|
|
let c1 = _Node(offset: c0.offset &+ 1, level: c0.level)
|
|
if c1.offset < count {
|
|
return maxValue(c0, c1)
|
|
}
|
|
|
|
return c0
|
|
}
|
|
}
|
|
|
|
extension Heap._UnsafeHandle {
|
|
@inlinable
|
|
internal func heapify() {
|
|
let limit = count / 2 // The first offset without a left child
|
|
var level = _Node.level(forOffset: limit &- 1)
|
|
while level >= 0 {
|
|
let nodes = _Node.allNodes(onLevel: level, limit: limit)
|
|
if _Node.isMinLevel(level) {
|
|
nodes?._forEach { node in
|
|
trickleDownMin(node)
|
|
}
|
|
} else {
|
|
nodes?._forEach { node in
|
|
trickleDownMax(node)
|
|
}
|
|
}
|
|
level &-= 1
|
|
}
|
|
}
|
|
}
|