From cd339541686c6841a0482cc8dd78c810cf86874c Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 16 Aug 2021 22:28:55 -0700 Subject: [PATCH] [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 07ffd6591f2a790f6b84b668c06a188325d4eaf2. * [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(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 --- .../xcschemes/PriorityQueueModule.xcscheme | 3 +- .../PriorityQueueModule/Heap+Invariants.swift | 93 +--- .../Heap+UnsafeHandle.swift | 371 ++++++++++++++ Sources/PriorityQueueModule/Heap.swift | 484 +++--------------- Sources/PriorityQueueModule/_Node.swift | 174 +++++++ Tests/PriorityQueueTests/HeapTests.swift | 11 +- 6 files changed, 660 insertions(+), 476 deletions(-) create mode 100644 Sources/PriorityQueueModule/Heap+UnsafeHandle.swift create mode 100644 Sources/PriorityQueueModule/_Node.swift diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme index b34d2227..7e344592 100644 --- a/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme +++ b/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme @@ -26,7 +26,8 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> + shouldUseLaunchSchemeArgsEnv = "YES" + codeCoverageEnabled = "YES"> diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift index 3396df5a..61999115 100644 --- a/Sources/PriorityQueueModule/Heap+Invariants.swift +++ b/Sources/PriorityQueueModule/Heap+Invariants.swift @@ -14,78 +14,41 @@ import Foundation extension Heap { #if COLLECTIONS_INTERNAL_CHECKS - /// Iterates through all the levels in the heap, ensuring that items in min - /// levels are smaller than all their descendants and items in max levels - /// are larger than all their descendants. - /// - /// The min-max heap indices are structured like this: - /// - /// ``` - /// min 0 - /// max 1 2 - /// min 3 4 5 6 - /// max 7 8 9 10 11 12 13 14 - /// min 15... - /// ... - /// ``` - /// - /// The iteration happens in depth-first order, so the descendants of the - /// element at index 0 are checked to ensure they are >= that element. This is - /// repeated for each child of the element at index 0 (inverting the - /// comparison at each level). - /// - /// In the case of 7 elements total (spread across 3 levels), the checking - /// happens in the following order: - /// - /// ``` - /// compare >= 0: 1, 3, 4, 2, 5, 6 - /// compare <= 1: 3, 4 - /// compare >= 3: (no children) - /// compare >= 4: (no children) - /// compare <= 2: 5, 6 - /// compare >= 5: (no children) - /// compare >= 6: (no children) - /// ``` + /// Visits each item in the heap in depth-first order, verifying that the + /// contents satisfy the min-max heap property. @inlinable @inline(never) internal func _checkInvariants() { guard count > 1 else { return } - var indicesToVisit: [Int] = [0] + _checkInvariants(node: .root, min: nil, max: nil) + } - while let elementIdx = indicesToVisit.popLast() { - let element = _storage[elementIdx] - - let isMinLevel = _minMaxHeapIsMinLevel(elementIdx) - - var descendantIndicesToVisit = [Int]() - - // Add the children of this element to the outer loop (as we want to check - // that they are >= or <= their descendants as well) - if let rightIdx = _rightChildIndex(of: elementIdx) { - descendantIndicesToVisit.append(rightIdx) - indicesToVisit.append(rightIdx) + @inlinable + internal func _checkInvariants(node: _Node, min: Element?, max: Element?) { + let value = _storage[node.offset] + if let min = min { + precondition(value >= min, + "Element \(value) at \(node) is less than min \(min)") + } + if let max = max { + precondition(value <= max, + "Element \(value) at \(node) is greater than max \(max)") + } + let left = node.leftChild() + let right = node.rightChild() + if node.isMinLevel { + if left.offset < count { + _checkInvariants(node: left, min: value, max: max) } - if let leftIdx = _leftChildIndex(of: elementIdx) { - descendantIndicesToVisit.append(leftIdx) - indicesToVisit.append(leftIdx) + if right.offset < count { + _checkInvariants(node: right, min: value, max: max) } - - // Compare the current element against its descendants - while let idx = descendantIndicesToVisit.popLast() { - if isMinLevel { - precondition(element <= _storage[idx], - "Element '\(_storage[idx])' at index \(idx) should be >= '\(element)'") - } else { - precondition(element >= _storage[idx], - "Element '\(_storage[idx])' at index \(idx) should be <= '\(element)'") - } - - if let rightIdx = _rightChildIndex(of: idx) { - descendantIndicesToVisit.append(rightIdx) - } - if let leftIdx = _leftChildIndex(of: idx) { - descendantIndicesToVisit.append(leftIdx) - } + } else { + if left.offset < count { + _checkInvariants(node: left, min: min, max: value) + } + if right.offset < count { + _checkInvariants(node: right, min: min, max: value) } } } diff --git a/Sources/PriorityQueueModule/Heap+UnsafeHandle.swift b/Sources/PriorityQueueModule/Heap+UnsafeHandle.swift new file mode 100644 index 00000000..d20f10c0 --- /dev/null +++ b/Sources/PriorityQueueModule/Heap+UnsafeHandle.swift @@ -0,0 +1,371 @@ +//===----------------------------------------------------------------------===// +// +// 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 + + @inlinable @inline(__always) + init(_ buffer: UnsafeMutableBufferPointer) { + self.buffer = buffer + } + } + + @inlinable @inline(__always) + mutating func _update(_ 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 { + 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 + } + } +} diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift index c04e90e4..b40727b3 100644 --- a/Sources/PriorityQueueModule/Heap.swift +++ b/Sources/PriorityQueueModule/Heap.swift @@ -9,28 +9,36 @@ // //===----------------------------------------------------------------------===// -import Swift - /// A [Min-Max Heap](https://en.wikipedia.org/wiki/Min-max_heap) data structure. /// /// In a min-max heap, each node at an even level in the tree is less than all /// its descendants, while each node at an odd level in the tree is greater than /// all of its descendants. /// -/// The implementation is based off [Atkinson et al. Min-Max Heaps and -/// Generalized Priority Queues (1986)](http://akira.ruc.dk/~keld/teaching/algoritmedesign_f03/Artikler/02/Atkinson86.pdf). +/// The implementation is based on [Atkinson 1986]: /// -/// M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. October 1986. -/// Min-Max Heaps and Generalized Priority Queues. Communications of the ACM. -/// 29(10):996-1000. +/// [Atkinson 1986]: https://doi.org/10.1145/6617.6621 +/// +/// M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. +/// "Min-Max Heaps and Generalized Priority Queues." +/// *Communications of the ACM*, vol. 29, no. 10, Oct. 1986., pp. 996-1000, +/// doi:[10.1145/6617.6621](https://doi.org/10.1145/6617.6621) public struct Heap { @usableFromInline - internal var _storage: [Element] + internal var _storage: ContiguousArray + /// Creates an empty heap. + @inlinable + public init() { + _storage = [] + } +} + +extension Heap { /// A Boolean value indicating whether or not the heap is empty. /// /// - Complexity: O(1) - @inlinable + @inlinable @inline(__always) public var isEmpty: Bool { _storage.isEmpty } @@ -38,7 +46,7 @@ public struct Heap { /// The number of elements in the heap. /// /// - Complexity: O(1) - @inlinable + @inlinable @inline(__always) public var count: Int { _storage.count } @@ -52,13 +60,7 @@ public struct Heap { /// - Complexity: O(1) @inlinable public var unordered: [Element] { - _storage - } - - /// Creates an empty heap. - @inlinable - public init() { - _storage = [] + Array(_storage) } /// Inserts the given element into the heap. @@ -67,7 +69,10 @@ public struct Heap { @inlinable public mutating func insert(_ element: Element) { _storage.append(element) - _bubbleUp(elementAt: _storage.endIndex - 1) + + _update { handle in + handle.bubbleUp(_Node(offset: handle.count - 1)) + } _checkInvariants() } @@ -84,17 +89,17 @@ public struct Heap { /// - Complexity: O(1) @inlinable public func max() -> Element? { - switch _storage.count { - case 0, 1, 2: - // If count is 0, `last` will return `nil` - // If count is 1, the last (and only) item is the max - // If count is 2, the last item is the max (as it's the only item in the - // first max level) - return _storage.last - default: + _storage.withUnsafeBufferPointer { buffer in + guard buffer.count > 2 else { + // If count is 0, `last` will return `nil` + // If count is 1, the last (and only) item is the max + // If count is 2, the last item is the max (as it's the only item in the + // first max level) + return buffer.last + } // We have at least 3 items -- return the larger of the two in the first // max level - return Swift.max(_storage[1], _storage[2]) + return Swift.max(buffer[1], buffer[2]) } } @@ -103,8 +108,20 @@ public struct Heap { /// - Complexity: O(log `count`) @inlinable public mutating func popMin() -> Element? { - defer { _checkInvariants() } - return _remove(at: 0) + guard _storage.count > 0 else { return nil } + + var removed = _storage.removeLast() + + if _storage.count > 0 { + _update { handle in + let minNode = _Node.root + handle.swapAt(minNode, with: &removed) + handle.trickleDownMin(minNode) + } + } + + _checkInvariants() + return removed } /// Removes and returns the element with the highest priority, if available. @@ -112,19 +129,24 @@ public struct Heap { /// - Complexity: O(log `count`) @inlinable public mutating func popMax() -> Element? { - defer { _checkInvariants() } - switch _storage.count { - case 0, 1, 2: - // If count is 0, `popLast` will return `nil` - // If count is 1, the last (and only) item is the max - // If count is 2, the last item is the max (as it's the only item in the - // first max level) - return _storage.popLast() - default: - // The max item is the larger of the two items in the first max level - let maxIdx = _storage[2] > _storage[1] ? 2 : 1 - return _remove(at: maxIdx) + guard _storage.count > 2 else { return _storage.popLast() } + + var removed = _storage.removeLast() + + _update { handle in + if handle.count == 2 { + if handle[.leftMax] > removed { + handle.swapAt(.leftMax, with: &removed) + } + } else { + let maxNode = handle.maxValue(.rightMax, .leftMax) + handle.swapAt(maxNode, with: &removed) + handle.trickleDownMax(maxNode) + } } + + _checkInvariants() + return removed } /// Removes and returns the element with the lowest priority. @@ -146,358 +168,6 @@ public struct Heap { public mutating func removeMax() -> Element { return popMax()! } - - // MARK: - - - @inline(__always) - @inlinable - internal mutating func _bubbleUp(elementAt index: Int) { - guard let parentIdx = _parentIndex(of: index) else { - // We're already at the root -- can't go any further - return - } - - // Figure out if `index` is on an even or odd level - let levelIsMin = _minMaxHeapIsMinLevel(index) - - if levelIsMin { - if _storage[index] > _storage[parentIdx] { - _swapAt(index, parentIdx) - _bubbleUpMax(elementAt: parentIdx) - } else { - _bubbleUpMin(elementAt: index) - } - } else { - if _storage[index] < _storage[parentIdx] { - _swapAt(index, parentIdx) - _bubbleUpMin(elementAt: parentIdx) - } else { - _bubbleUpMax(elementAt: index) - } - } - } - - @inline(__always) - @inlinable - internal mutating func _bubbleUpMin(elementAt index: Int) { - var index = index - - while let grandparentIdx = _grandparentIndex(of: index), - _storage[index] < _storage[grandparentIdx] { - _swapAt(index, grandparentIdx) - index = grandparentIdx - } - } - - @inline(__always) - @inlinable - internal mutating func _bubbleUpMax(elementAt index: Int) { - var index = index - - while let grandparentIdx = _grandparentIndex(of: index), - _storage[index] > _storage[grandparentIdx] { - _swapAt(index, grandparentIdx) - index = grandparentIdx - } - } - - // MARK: - - - @discardableResult - @inlinable - internal mutating func _remove(at index: Int) -> Element? { - guard _storage.count > index else { - return nil - } - - var removed = _storage.removeLast() - - if index < _storage.count { - swap(&removed, &_storage[index]) - _trickleDown(elementAt: index) - } - - return removed - } - - // MARK: - - - @inline(__always) - @inlinable - internal mutating func _trickleDown(elementAt index: Int) { - // Figure out if `index` is on an even or odd level - let levelIsMin = _minMaxHeapIsMinLevel(index) - - if levelIsMin { - _trickleDownMin(elementAt: index) - } else { - _trickleDownMax(elementAt: index) - } - } - - @inline(__always) - @inlinable - internal mutating func _trickleDownMin(elementAt index: Int) { - var index = index - - while let (smallestDescendantIdx, isChild) = - _indexOfLowestPriorityChildOrGrandchild(of: index) { - if _storage[smallestDescendantIdx] < _storage[index] { - _swapAt(smallestDescendantIdx, index) - - if isChild { - return - } - - // Smallest is a grandchild - let parentIdx = _parentIndex(of: smallestDescendantIdx)! - if _storage[smallestDescendantIdx] > _storage[parentIdx] { - _swapAt(smallestDescendantIdx, parentIdx) - } - - index = smallestDescendantIdx - } else { - return - } - } - } - - @inline(__always) - @inlinable - internal mutating func _trickleDownMax(elementAt index: Int) { - var index = index - - while let (largestDescendantIdx, isChild) = - _indexOfHighestPriorityChildOrGrandchild(of: index) { - if _storage[largestDescendantIdx] > _storage[index] { - _swapAt(largestDescendantIdx, index) - - if isChild { - return - } - - // Largest is a grandchild - let parentIdx = _parentIndex(of: largestDescendantIdx)! - if _storage[largestDescendantIdx] < _storage[parentIdx] { - _swapAt(largestDescendantIdx, parentIdx) - } - - index = largestDescendantIdx - } else { - return - } - } - } - - /// Returns the lowest priority child or grandchild of the element at the - /// given index. - /// - /// Returns `nil` if the element has no descendants. - /// - /// - parameter index: The index of the element whose descendants should be - /// compared. - @inline(__always) - @inlinable - internal func _indexOfLowestPriorityChildOrGrandchild( - of index: Int - ) -> (index: Int, isChild: Bool)? { - guard let leftChildIdx = _leftChildIndex(of: index) else { - return nil - } - - var result: (index: Int, isChild: Bool) = (leftChildIdx, true) - - guard let rightChildIdx = _rightChildIndex(of: index) else { - return result - } - - guard let firstGrandchildIdx = _firstGrandchildIndex(of: index), - let lastGrandchildIdx = _lastGrandchildIndex(of: index) - else { - // We have no grandchildren -- compare the two children instead - if _storage[rightChildIdx] < _storage[leftChildIdx] { - result.index = rightChildIdx - } - - return result - } - - // If we have 4 grandchildren, we can skip comparing the children as the - // heap invariants will ensure that the grandchildren will be smaller. - // Otherwise, we need to do the comparison. - if lastGrandchildIdx != firstGrandchildIdx + 3 { - // Compare the two children - if _storage[rightChildIdx] < _storage[leftChildIdx] { - result.index = rightChildIdx - } - } - - // Iterate through the grandchildren - for i in firstGrandchildIdx...lastGrandchildIdx { - if _storage[i] < _storage[result.index] { - result.index = i - result.isChild = false - } - } - - return result - } - - /// Returns the highest priority child or grandchild of the element at the - /// given index. - /// - /// Returns `nil` if the element has no descendants. - /// - /// - parameter index: The index of the item whose descendants should be - /// compared. - @inline(__always) - @inlinable - internal func _indexOfHighestPriorityChildOrGrandchild( - of index: Int - ) -> (index: Int, isChild: Bool)? { - guard let leftChildIdx = _leftChildIndex(of: index) else { - return nil - } - - var result: (index: Int, isChild: Bool) = (leftChildIdx, true) - - guard let rightChildIdx = _rightChildIndex(of: index) else { - return result - } - - guard let firstGrandchildIdx = _firstGrandchildIndex(of: index), - let lastGrandchildIdx = _lastGrandchildIndex(of: index) - else { - // We have no grandchildren -- compare the two children instead - if _storage[rightChildIdx] > _storage[leftChildIdx] { - result.index = rightChildIdx - } - - return result - } - - // If we have 4 grandchildren, we can skip comparing the children as the - // heap invariants will ensure that the grandchildren will be larger. - // Otherwise, we need to do the comparison. - if lastGrandchildIdx != firstGrandchildIdx + 3 { - // Compare the two children - if _storage[rightChildIdx] > _storage[leftChildIdx] { - result.index = rightChildIdx - } - } - - // Iterate through the grandchildren - for i in firstGrandchildIdx...lastGrandchildIdx { - if _storage[i] > _storage[result.index] { - result.index = i - result.isChild = false - } - } - - return result - } - - // MARK: - Helpers - - /// Returns `true` if `index` falls on a min level in a min-max heap. - /// - /// - Precondition: `index` must be non-negative. - @inline(__always) - @inlinable - internal func _minMaxHeapIsMinLevel(_ index: Int) -> Bool { - precondition(index >= 0) - - return (index + 1)._binaryLogarithm() & 0b1 == 0 - } - - /// Swaps the elements in the heap at the given indices. - @inline(__always) - @inlinable - internal mutating func _swapAt(_ i: Int, _ j: Int) { - let tmp = _storage[i] - _storage[i] = _storage[j] - _storage[j] = tmp - } - - /// Returns the parent index of the given `index` - /// or `nil` if the index has no parent (i.e. `index == 0`). - @inline(__always) - @inlinable - internal func _parentIndex(of index: Int) -> Int? { - guard index > 0 else { - return nil - } - - return (index - 1) / 2 - } - - /// Returns the grandparent index of the given `index` - /// or `nil` if the index has no grandparent. - @inline(__always) - @inlinable - internal func _grandparentIndex(of index: Int) -> Int? { - guard index > 2 else { - return nil - } - - return (index - 3) / 4 - } - - /// Returns the first child index of the given `index` - /// or `nil` if the index has no children. - @inline(__always) - @inlinable - internal func _leftChildIndex(of index: Int) -> Int? { - let childIdx = index * 2 + 1 - guard childIdx < _storage.count else { - return nil - } - - return childIdx - } - - /// Returns the right child index of the given `index` - /// or `nil` if the index has no right child. - @inline(__always) - @inlinable - internal func _rightChildIndex(of index: Int) -> Int? { - let childIdx = index * 2 + 2 - guard childIdx < _storage.count else { - return nil - } - - return childIdx - } - - /// Returns the first grandchild index of the given `index` - /// or `nil` if the index has no grandchildren. - @inline(__always) - @inlinable - internal func _firstGrandchildIndex(of index: Int) -> Int? { - let grandchildIdx = index * 4 + 3 - guard grandchildIdx < _storage.count else { - return nil - } - - return grandchildIdx - } - - /// Returns the last valid grandchild index of the given `index` - /// or `nil` if the index has no grandchildren. - /// - /// In cases where the given index only has one grandchild, the index - /// returned by this function is the same as that returned by - /// `_firstGrandchildIndex`. - @inline(__always) - @inlinable - internal func _lastGrandchildIndex(of index: Int) -> Int? { - guard _firstGrandchildIndex(of: index) != nil else { - // There are no grandchildren of the node at `index` - return nil - } - - return Swift.min(index * 4 + 6, _storage.count - 1) - } } // MARK: - @@ -505,17 +175,20 @@ public struct Heap { extension Heap { /// Initializes a heap from a sequence. /// - /// Utilizes [Floyd's linear-time heap construction algorithm](https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction). - /// - /// - Complexity: O(n), where `n` is the length of `elements`. + /// - Complexity: O(*n*), where *n* is the length of `elements`. @inlinable public init(_ elements: S) where S.Element == Element { - _storage = Array(elements) + // This is Floyd's linear-time heap construction algorithm. + // (https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction). + // + // FIXME: See if a more cache friendly algorithm would be faster. - for idx in (0 ..< (_storage.count / 2)).reversed() { - _trickleDown(elementAt: idx) + _storage = ContiguousArray(elements) + guard _storage.count > 1 else { return } + + _update { handle in + handle.heapify() } - _checkInvariants() } @@ -523,9 +196,16 @@ extension Heap { /// /// - Parameter newElements: The new elements to insert into the heap. /// - /// - Complexity: O(n * log `count`), where `n` is the length of `newElements`. + /// - Complexity: O(*n* * log(`count`)), where *n* is the length of `newElements`. @inlinable - public mutating func insert(contentsOf newElements: S) where S.Element == Element { + public mutating func insert( + contentsOf newElements: S + ) where S.Element == Element { + if count == 0 { + self = Self(newElements) + return + } + _storage.reserveCapacity(count + newElements.underestimatedCount) for element in newElements { insert(element) } diff --git a/Sources/PriorityQueueModule/_Node.swift b/Sources/PriorityQueueModule/_Node.swift new file mode 100644 index 00000000..02927814 --- /dev/null +++ b/Sources/PriorityQueueModule/_Node.swift @@ -0,0 +1,174 @@ +//===----------------------------------------------------------------------===// +// +// 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? { + 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 + } + } +} diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift index 12b6b03b..880e0c8a 100644 --- a/Tests/PriorityQueueTests/HeapTests.swift +++ b/Tests/PriorityQueueTests/HeapTests.swift @@ -350,18 +350,13 @@ final class HeapTests: XCTestCase { func test_levelCalculation() { // Check alternating min and max levels in the heap - let q = Heap() var isMin = true for exp in 0...12 { // Check [2^exp, 2^(exp + 1)) - for i in Int(pow(2, Double(exp)) - 1)..