# OperationQueue dequeue and remove operations performance improvement

**URL:** <https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370>\
**Category:** Core Libraries\
**Tags:** foundation\
**Created:** [February 11, 2019, 11:22pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370 "2019-02-11T23:22:30Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![karthikkeyan.balan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/karthikkeyan.balan/32/21168_2.png) [@karthikkeyan.balan](https://forums.swift.org/u/karthikkeyan.balan)\
**Post date:** [February 11, 2019, 11:22pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/1 "2019-02-11T23:22:31Z")

</div>

Hi Guys,

I was going through `Operation.swift`'s code and I noticed an opportunity to improve the time complexity of operations like dequeue and remove.

The current implementation of `OperationQueue` uses an internal `struct` called [`_OperationList`](https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/Operation.swift#L237) which contains 6 arrays of operations,

```swift
struct _OperationList {
    var veryLow = [Operation]()
    var low = [Operation]()
    var normal = [Operation]()
    var high = [Operation]()
    var veryHigh = [Operation]()
    var all = [Operation]()
}

```

When an operation is cancelled or finished, `OperationQueue` is calling `_OperatonList.removing(_:Operation)` method and when an operation is dequeued `_OperationList.dequeue()` is calling.

Now, given the nature of `OperationQueue`, which frequently adds, dequeues and removes operations from the queue, the program end up running at **0(n)** runtime, for search and delete, as the operations are performed on **Array** data structure.

Im thinking this **O(n)** time can be reduced down to **O(1)** if we use **LinkedList** and **HashTable** together.

Heres the updated interface,

**Double Linked List**

```swift
internal class _IndexedOperationLinkedList {
    internal class Node {
        var operation: Operation
        var next: _IndexedOperationLinkedList.Node? = nil
        var previous: _IndexedOperationLinkedList.Node? = nil
    }
    
    private(set) var root: _IndexedOperationLinkedList.Node? = nil
    private(set) weak var tail: _IndexedOperationLinkedList.Node? = nil
    private(set) var count: Int = 0
    private var nodeForOperation: [Operation: _IndexedOperationLinkedList.Node] = [:]
    
    func insert(_ operation: Operation) { }
    func remove(_ operation: Operation) { }
    func removeFirst() -> Operation? { } 
    func map<T>(_ transform: (Operation) throws -> T) rethrows -> [T] { }
}

```

**\_OperationList**

```swift
internal struct _OperationList {
    var veryLow = _IndexedOperationLinkedList()
    var low = _IndexedOperationLinkedList()
    var normal = _IndexedOperationLinkedList()
    var high = _IndexedOperationLinkedList()
    var veryHigh = _IndexedOperationLinkedList()
    var all = _IndexedOperationLinkedList()
    
    mutating func insert(_ operation: Operation) {
        all.insert(operation)
        
        switch operation.queuePriority {
        case .veryLow:
            veryLow.insert(operation)
        case .low:
            low.insert(operation)
        case .normal:
            normal.insert(operation)
        case .high:
            high.insert(operation)
        case .veryHigh:
            veryHigh.insert(operation)
        }
    }
    
    mutating func remove(_ operation: Operation) {
        all.remove(operation)
        
        switch operation.queuePriority {
        case .veryLow:
            veryLow.remove(operation)
        case .low:
            low.remove(operation)
        case .normal:
            normal.remove(operation)
        case .high:
            high.remove(operation)
        case .veryHigh:
            veryHigh.remove(operation)
        }
    }
    
    mutating func dequeue() -> Operation? {
        if let operation = veryHigh.removeFirst() {
            return operation
        }
        if let operation = high.removeFirst() {
            return operation
        }
        if let operation = normal.removeFirst() {
            return operation
        }
        if let operation = low.removeFirst() {
            return operation
        }
        if let operation = veryLow.removeFirst() {
            return operation
        }
        return nil
    }
    
    func map<T>(_ transform: (Operation) throws -> T) rethrows -> [T] {
        return try all.map(transform)
    }
}

```

Please give me your suggestions.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [February 11, 2019, 11:54pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/2 "2019-02-11T23:54:15Z")

</div>

Have you tested the performance of this? Array's theoretical O(n) performance often beats a linked list's O(1) in practice because of cache locality and avoiding memory allocations. Of course, _I_ haven't looked at this, so maybe it _is_ a win in this case.

---

<div class="post-metadata">

**Author:** ![karthikkeyan.balan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/karthikkeyan.balan/32/21168_2.png) [@karthikkeyan.balan](https://forums.swift.org/u/karthikkeyan.balan)\
**Post date:** [February 12, 2019, 1:17am UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/3 "2019-02-12T01:17:35Z")

</div>

@jrose thanks for the quick response.

Yes, I have performed measurement test using `XCTest.measure { }`, although I don't have the baseline for this measurement, the numbers I see for linked list based implementation is better than the array implementation.

Heres the test code snippet for the test,

```swift
    func test_OperationQueuePerformanceMeasurement() {
        let priorities: [Operation.QueuePriority] = [.veryHigh, .high, .normal, .low, .veryLow]
        
        let queue = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        measure {
            var operations = [Operation]()
            for _ in 0...1000 {
                let operation = BlockOperation(block: { })
                operation.queuePriority = priorities.randomElement() ?? .normal
                operations.append(operation)
            }
            
            queue.addOperations(operations, waitUntilFinished: true)
        }
    }

```

I tried measurement for both, current and linked list implementation, with 1000, 500, 100, 10 number of operations. The results are below,

### Current Implementation

**1000 Operations**  
average: 4.059  
relative standard deviation: 5.279%  
values: [4.118417, 3.810524, 4.005855, 4.614813, 4.090776, 3.996997, 4.058232, 3.924490, 4.024753, 3.948501]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

**500 Operations**  
average: 1.162  
relative standard deviation: 3.986%  
values: [1.194851, 1.218860, 1.120588, 1.189215, 1.196692, 1.087050, 1.196618, 1.098075, 1.175428, 1.145848]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

**10 Operations**  
average: 0.003  
relative standard deviation: 8.285%  
values: [0.003790, 0.003167, 0.003243, 0.003103, 0.003118, 0.003006, 0.002971, 0.003039, 0.002859, 0.002953]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

--

### Linked List Implementation

**1000 Operations**  
average: 0.173  
relative standard deviation: 3.914%  
values: [0.178822, 0.180436, 0.178626, 0.180535, 0.165167, 0.163331, 0.176456, 0.174253, 0.168144, 0.166332]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

**500 Operations**  
average: 0.102  
relative standard deviation: 3.473%  
values: [0.101013, 0.097204, 0.096554, 0.107769, 0.104321, 0.102416, 0.104235, 0.106209, 0.101869, 0.102254]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

**100 Operations**  
average: 0.018  
relative standard deviation: 4.641%  
values: [0.017459, 0.017175, 0.017106, 0.017388, 0.018774, 0.019306, 0.018784, 0.019071, 0.018116, 0.018749]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

**10 Operations**  
average: 0.002  
relative standard deviation: 6.390%  
values: [0.002861, 0.002572, 0.002399, 0.002386, 0.002376, 0.002443, 0.002455, 0.002348, 0.002348, 0.002376]  
maxPercentRelativeStandardDeviation: 10.000%  
maxStandardDeviation: 0.100

--

Looking at the numbers, the trend Im seeing is that, as the number of operations increases, the linked list based implementation's performance looks better than array based implementation.

Hope Im doing the measurement correct, please correct me if Im wrong.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [February 12, 2019, 1:20am UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/4 "2019-02-12T01:20:15Z")

</div>

Okay, then maybe it is worth it! @millenomi, what do you think?

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [February 12, 2019, 1:40am UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/5 "2019-02-12T01:40:58Z")

</div>

Speaking as someone with zero expertise nor experience here, from a purely theoretical perspective I would have rather expected to see a priority queue being used for this type of application.

---

<div class="post-metadata">

**Author:** ![TellowKrinkle](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tellowkrinkle/32/3370_2.png) [@TellowKrinkle](https://forums.swift.org/u/TellowKrinkle)\
**Post date:** [February 12, 2019, 2:00am UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/6 "2019-02-12T02:00:19Z")

</div>

> [@karthikkeyan.balan](#):
>
> ```swift
> var previous: _IndexedOperationLinkedList.Node? = nil
> 
> ```

Shouldn't this be `weak` or `unowned`?

---

<div class="post-metadata">

**Author:** ![karthikkeyan.balan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/karthikkeyan.balan/32/21168_2.png) [@karthikkeyan.balan](https://forums.swift.org/u/karthikkeyan.balan)\
**Post date:** [February 12, 2019, 2:24am UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/7 "2019-02-12T02:24:37Z")

</div>

Hi Nevin,

I thought about implementing Priority Queue, but following are the reasons I decided to go with linked list based approach,

- Priority queue do insert and delete-next-prioritized-item in **O(log N)** time.
- We need random access to the elements in queue, not just the first element. Finding that element is again is **O(n)** time
- Besides, Im guessing, it is gonna be quite a challenge to keep the operations of same priority, in the same order as it was added in the queue.

In linked list based approach we could do insert, delete-next-prioritized in O(1) and with the use of hash map deleting a random item also comes down to O(1).

Hope I made a correct decision.

---

<div class="post-metadata">

**Author:** ![karthikkeyan.balan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/karthikkeyan.balan/32/21168_2.png) [@karthikkeyan.balan](https://forums.swift.org/u/karthikkeyan.balan)\
**Post date:** [February 12, 2019, 2:41am UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/8 "2019-02-12T02:41:45Z")

</div>

Thanks @TellowKrinkle, good catch. I will update the property `previous` as a `weak` reference. You have saved a potential retain cycle.

---

<div class="post-metadata">

**Author:** ![Philippe\_Hausler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/philippe_hausler/32/22569_2.png) [@Philippe\_Hausler](https://forums.swift.org/u/Philippe_Hausler)\
**Post date:** [February 12, 2019, 5:07pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/9 "2019-02-12T17:07:35Z")

</div>

FYI NSOperationQueue (objc) uses a doubly linked list with the heads stored in the queue and next/prev stored in the NSOperations (all of these are stored as unsafe references balanced by a retain on add and a release on finish/cancel). It is worth noting there are a few caveats from a threading perspective: 1) all mutations to the list are done under the lock from the queue, and 2) the queue is strongly referenced by the operations and cleared after finished/cancelled.

---

<div class="post-metadata">

**Author:** ![karthikkeyan.balan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/karthikkeyan.balan/32/21168_2.png) [@karthikkeyan.balan](https://forums.swift.org/u/karthikkeyan.balan)\
**Post date:** [February 12, 2019, 8:22pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/10 "2019-02-12T20:22:58Z")

</div>

Hi @Philippe_Hausler

Sorry, Im unable to completely understand your reply. Are you suggesting any changes to my approach or a different approach altogether? Or Is this proposed solution of mine good to go?

---

<div class="post-metadata">

**Author:** ![Philippe\_Hausler](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/philippe_hausler/32/22569_2.png) [@Philippe\_Hausler](https://forums.swift.org/u/Philippe_Hausler)\
**Post date:** [February 12, 2019, 8:24pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/11 "2019-02-12T20:24:20Z")

</div>

I am saying that your approach is accurate to how the objc version is implemented. In short; I think it is a salient method of implementing it and is worthwhile to eek out some more perf here.

---

<div class="post-metadata">

**Author:** ![karthikkeyan.balan](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/karthikkeyan.balan/32/21168_2.png) [@karthikkeyan.balan](https://forums.swift.org/u/karthikkeyan.balan)\
**Post date:** [February 12, 2019, 8:28pm UTC](https://forums.swift.org/t/operationqueue-dequeue-and-remove-operations-performance-improvement/20370/12 "2019-02-12T20:28:07Z")

</div>

Thanks @Philippe_Hausler
