Files
swift-nio/Tests/NIOTests/PriorityQueueTests.swift
T
Cory Benfield 831cf89d54 Reduce refcounting in Heap by removing configurability (#1614)
Motivation:

Right now Heap.heapify incurs quite a lot of ARC traffic when it is used
in SelectableEventLoop. Specifically, each of the invocations of
self.comparator in heapify incurs three refcount operations. These three
are all the result of the fact that the comparator is an arbitrary
function, but all three are guaranteed to be unnecessary.

The first refcount is for the closure context for self.comparator. Of
course, self.comparator has only two possible values, neither of which
needs a closure context, but the compiler doesn't know that and the type
system doesn't encode it.

The other two refcounts are for the ScheduledTask objects themselves.
Again, the compiler doesn't know what the comparator function will do,
so it must defensively ensure that a retain/release is inserted for the
arguments of that function.

If we happen to hit both branches of the code, we'll execute 6 retains
and 6 releases, and even in fairly average cases we'll execute 3 of
each.

All of this is unnecessary: the only runtime function ever used here is
a trivial comparison operation. We know what it is at compile time, we
just have to ask. While it was admirable to have the configurability of
the priority queue in place, after 3 years I think we have a pretty good
feeling that we're not going to need the ability to have a max-heap
instead of a min-heap.

We can always get this back if we need it.

Modifications:

- Removed the configurability of Heap.
- Removed HeapType.
- Removed arguments from PriorityQueue
- Removed all tests testing now-removed max-heap functionality.

Result:

Less ARC traffic in the core task scheduling loop.
2020-08-10 13:12:43 +01:00

151 lines
4.9 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import NIO
class PriorityQueueTest: XCTestCase {
func testSomeStringsAsc() throws {
var pq = PriorityQueue<String>()
pq.push("foo")
pq.push("bar")
pq.push("buz")
pq.push("qux")
pq.remove("buz")
XCTAssertEqual("bar", pq.peek()!)
XCTAssertEqual("bar", pq.pop()!)
pq.push("bar")
XCTAssertEqual("bar", pq.peek()!)
XCTAssertEqual("bar", pq.pop()!)
XCTAssertEqual("foo", pq.pop()!)
XCTAssertEqual("qux", pq.pop()!)
XCTAssertTrue(pq.isEmpty)
}
func testRemoveNonExisting() throws {
var pq = PriorityQueue<String>()
pq.push("foo")
pq.remove("bar")
pq.remove("foo")
XCTAssertNil(pq.pop())
XCTAssertNil(pq.peek())
}
func testRemoveFromEmpty() throws {
var pq = PriorityQueue<Int>()
pq.remove(234)
XCTAssertTrue(pq.isEmpty)
}
func testBuildAndRemoveFromRandomPriorityQueues() {
for size in 0...33 {
var pq = PriorityQueue<UInt8>()
let randoms = getRandomNumbers(count: size)
randoms.forEach { pq.push($0) }
/* remove one random member, add it back and assert we're still the same */
randoms.forEach { random in
var pq2 = pq
pq2.remove(random)
XCTAssertEqual(pq.count - 1, pq2.count)
XCTAssertNotEqual(pq, pq2)
pq2.push(random)
XCTAssertEqual(pq, pq2)
}
/* remove up to `n` members and add them back at the end and check that the priority queues are still the same */
for n in 1...5 where n <= size {
var pq2 = pq
let deleted = randoms.prefix(n).map { (random: UInt8) -> UInt8 in
pq2.remove(random)
return random
}
XCTAssertEqual(pq.count - n, pq2.count)
XCTAssertNotEqual(pq, pq2)
deleted.reversed().forEach { pq2.push($0) }
XCTAssertEqual(pq, pq2, "pq: \(pq), pq2: \(pq2), deleted: \(deleted)")
}
}
}
func testPartialOrder() {
let clearlyTheSmallest = SomePartiallyOrderedDataType(width: 0, height: 0)
let clearlyTheLargest = SomePartiallyOrderedDataType(width: 100, height: 100)
let inTheMiddles = zip(1...99, (1...99).reversed()).map { SomePartiallyOrderedDataType(width: $0, height: $1) }
/*
the four values are only partially ordered (from small (top) to large (bottom)):
clearlyTheSmallest
/ | \
inTheMiddle[0] | inTheMiddle[1...]
\ | /
clearlyTheLargest
*/
var pq = PriorityQueue<SomePartiallyOrderedDataType>()
pq.push(clearlyTheLargest)
pq.push(inTheMiddles[0])
pq.push(clearlyTheSmallest)
inTheMiddles[1...].forEach {
pq.push($0)
}
let pop1 = pq.pop()
XCTAssertEqual(clearlyTheSmallest, pop1)
for _ in inTheMiddles {
let popN = pq.pop()!
XCTAssert(inTheMiddles.contains(popN))
}
XCTAssertEqual(clearlyTheLargest, pq.pop()!)
XCTAssert(pq.isEmpty)
}
func testDescription() {
let pq1 = PriorityQueue<Int>()
var pq2 = PriorityQueue<Int>()
pq2.push(1)
pq2.push(2)
pq2.push(3)
XCTAssertEqual(pq1.description, "PriorityQueue(count: 0): \(Array(pq1))")
XCTAssertEqual(pq2.description, "PriorityQueue(count: 3): \(Array(pq2))")
}
}
/// This data type is only partially ordered. Ie. from `a < b` and `a != b` we can't imply `a > b`.
struct SomePartiallyOrderedDataType: Comparable, CustomStringConvertible {
public static func <(lhs: SomePartiallyOrderedDataType, rhs: SomePartiallyOrderedDataType) -> Bool {
return lhs.width < rhs.width && lhs.height < rhs.height
}
public static func ==(lhs: SomePartiallyOrderedDataType, rhs: SomePartiallyOrderedDataType) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
private let width: Int
private let height: Int
public init(width: Int, height: Int) {
self.width = width
self.height = height
}
public var description: String {
return "(w: \(self.width), h: \(self.height))"
}
}