# RFC: Deque: should it have a capacity?

**URL:** <https://forums.swift.org/t/rfc-deque-should-it-have-a-capacity/47204>\
**Category:** Collections\
**Created:** [April 6, 2021, 3:34pm UTC](https://forums.swift.org/t/rfc-deque-should-it-have-a-capacity/47204 "2021-04-06T15:34:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![johannesweiss](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/johannesweiss/32/38183_2.png) [@johannesweiss](https://forums.swift.org/u/johannesweiss)\
**Post date:** [April 6, 2021, 3:34pm UTC](https://forums.swift.org/t/rfc-deque-should-it-have-a-capacity/47204/1 "2021-04-06T15:34:48Z")

</div>

`Deque` documents

> They also lack a `capacity` property -- the size of the  
> storage buffer at any given point is an unstable implementation detail that  
> should not affect application logic.

I find this somewhat unconvincing because `Deque`s are often used for buffering and in many cases we want to prevent holding onto a (temporarily) ballooned `Deque`. For example in SwiftNIO we have [code](https://github.com/apple/swift-nio/blob/c5a214f07588fc9bdf41b6e6a2b14384d6d0c2e4/Sources/NIO/Codec.swift#L290) which does:

```swift
self.buffers.removeAll(keepingCapacity: self.buffers.capacity < 16) // don't grow too much

```

and the idea is that we want to hold onto `self.buffers` (a deque) but only if its underlying storage buffer is 16 elements or less at the moment. This occurred to me when I was [reimplementing `CircularBuffer` on top of `Deque`](https://github.com/apple/swift-nio/pull/1792).

---

<div class="post-metadata">

**Author:** ![lorentey](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/lorentey/32/1299_2.png) [@lorentey](https://forums.swift.org/u/lorentey)\
**Post date:** [April 7, 2021, 6:28am UTC](https://forums.swift.org/t/rfc-deque-should-it-have-a-capacity/47204/2 "2021-04-07T06:28:48Z")

</div>

That’s a good reason to provide a capacity. 🤔

But what if we instead made `Deque` automatically shrink its storage on removals instead? (And provided an `init(minimumCapacity:persistent:)` initializer, like [`OrderedSet`](https://github.com/apple/swift-collections/blob/main/Sources/OrderedCollections/OrderedSet/OrderedSet%2BReserveCapacity.swift#L13-L40).)

> If you have a good idea of the expected working size of the set, calling this initializer with `persistent` set to true can sometimes improve performance by eliminating churn due to repeated rehashings when the set temporarily shrinks below its regular size.
> 
> - Parameter minimumCapacity: The minimum number of elements that the newly created set should be able to store without reallocating its storage.
> 
> - Parameter persistent: If set to true, prevent removals from shrinking storage below the specified capacity. By default, removals are allowed to shrink storage below any previously reserved capacity.
