Files
swift-collections/Sources/PriorityQueueModule/_Node.swift
T
Karoy Lorentey cd33954168 [Heap] Performance tweaks (#78)
* [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
2021-08-16 22:28:55 -07:00

175 lines
4.5 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
//
//===----------------------------------------------------------------------===//
@usableFromInline @frozen
internal struct _Node {
@usableFromInline
internal var offset: Int
@usableFromInline
internal var level: Int
@inlinable
internal init(offset: Int, level: Int) {
assert(offset >= 0)
#if COLLECTIONS_INTERNAL_CHECKS
assert(level == Self.level(forOffset: offset))
#endif
self.offset = offset
self.level = level
}
@inlinable
internal init(offset: Int) {
self.init(offset: offset, level: Self.level(forOffset: offset))
}
}
extension _Node: Comparable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left.offset == right.offset
}
@inlinable @inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left.offset < right.offset
}
}
extension _Node: CustomStringConvertible {
@usableFromInline
internal var description: String {
"(offset: \(offset), level: \(level))"
}
}
extension _Node {
@inlinable @inline(__always)
internal static func level(forOffset offset: Int) -> Int {
(offset &+ 1)._binaryLogarithm()
}
@inlinable @inline(__always)
internal static func firstNode(onLevel level: Int) -> _Node {
assert(level >= 0)
return _Node(offset: (1 &<< level) &- 1, level: level)
}
@inlinable @inline(__always)
internal static func lastNode(onLevel level: Int) -> _Node {
assert(level >= 0)
return _Node(offset: (1 &<< (level &+ 1)) &- 2, level: level)
}
@inlinable @inline(__always)
internal static func isMinLevel(_ level: Int) -> Bool {
level & 0b1 == 0
}
}
extension _Node {
/// The root node in the heap.
@inlinable @inline(__always)
internal static var root: Self {
Self.init(offset: 0, level: 0)
}
/// The first max node in the heap. (I.e., the left child of the root.)
@inlinable @inline(__always)
internal static var leftMax: Self {
Self.init(offset: 1, level: 1)
}
/// The second max node in the heap. (I.e., the right child of the root.)
@inlinable @inline(__always)
internal static var rightMax: Self {
Self.init(offset: 2, level: 1)
}
@inlinable @inline(__always)
internal var isMinLevel: Bool {
Self.isMinLevel(level)
}
@inlinable @inline(__always)
internal var isRoot: Bool {
offset == 0
}
}
extension _Node {
/// Returns the parent of this index, or `nil` if the index has no parent
/// (i.e. when this is the root index).
@inlinable @inline(__always)
internal func parent() -> Self {
assert(!isRoot)
return Self(offset: (offset &- 1) / 2, level: level &- 1)
}
/// Returns the grandparent of this index, or `nil` if the index has
/// no grandparent.
@inlinable @inline(__always)
internal func grandParent() -> Self? {
guard offset > 2 else { return nil }
return Self(offset: (offset &- 3) / 4, level: level &- 2)
}
/// Returns the left child of this node.
@inlinable @inline(__always)
internal func leftChild() -> Self {
Self(offset: offset &* 2 &+ 1, level: level &+ 1)
}
/// Returns the right child of this node.
@inlinable @inline(__always)
internal func rightChild() -> Self {
Self(offset: offset &* 2 &+ 2, level: level &+ 1)
}
@inlinable @inline(__always)
internal func firstGrandchild() -> Self {
Self(offset: offset &* 4 &+ 3, level: level &+ 2)
}
@inlinable @inline(__always)
internal func lastGrandchild() -> Self {
Self(offset: offset &* 4 &+ 6, level: level &+ 2)
}
@inlinable
internal static func allNodes(
onLevel level: Int,
limit: Int
) -> ClosedRange<Self>? {
let first = Self.firstNode(onLevel: level)
guard first.offset < limit else { return nil }
var last = self.lastNode(onLevel: level)
if last.offset >= limit {
last = _Node(offset: limit &- 1, level: level)
}
return ClosedRange(uncheckedBounds: (first, last))
}
}
extension ClosedRange where Bound == _Node {
@inlinable @inline(__always)
internal func _forEach(_ body: (_Node) -> Void) {
assert(
isEmpty || _Node.level(forOffset: upperBound.offset) == lowerBound.level)
var node = self.lowerBound
while node.offset <= self.upperBound.offset {
body(node)
node.offset &+= 1
}
}
}