In Swift, what does Array.append cost, when does reserveCapacity(_:) help, and why is removing from the front slow?
answer
- geometric growth of storage
- capacity versus count
- shifting every later element
- a slice's moving start index
basics
~10 sArray.append(:) is O(1) on average because storage grows geometrically. reserveCapacity(:) avoids repeated reallocations when the final size is known. insert(_:at: 0) and removeFirst() are O(n) because every later element shifts.
solid answer
~40 sAn `Array` keeps a buffer with spare **capacity**. When `append(_:)` overflows it, the array allocates a larger buffer, a multiple of the old size, and moves the elements, so over many calls append averages O(1). If I know the final size, one `reserveCapacity(_:)` up front removes those reallocations. Calling it inside a loop with `count + 10` is a documented anti-pattern: it forces linear growth and can make appends linear. Removing or inserting at the front is O(n) because elements shift, so a loop of `removeFirst()` over a big array is quadratic. For a queue I walk an `ArraySlice` with `popFirst()`, which is O(1), or pop from the end with `removeLast()`.
code
swift · 23 linesfunc loadThumbnail(_ id: Int) { /* decode and cache */ }
let pendingIDs = Array(0..<50_000)
// Quadratic: each removeFirst() shifts every remaining element left.
var queue = pendingIDs
while !queue.isEmpty {
loadThumbnail(queue.removeFirst())
}
// Linear: walk a slice instead; ArraySlice.popFirst() only moves startIndex.
var remaining = pendingIDs[...]
while let id = remaining.popFirst() {
loadThumbnail(id)
}
// Building a result whose size is known up front: reserve once, then append.
var visible: [Int] = []
visible.reserveCapacity(pendingIDs.count)
for id in pendingIDs where id % 2 == 0 {
visible.append(id)
}
print(visible.count, visible.capacity >= pendingIDs.count)go deeper
Recall that appending to an array is cheap on average and that inserting or removing at the front is linear because elements shift.
Explain count versus capacity, geometric growth, why append is amortized constant time, and when reserving capacity removes reallocations.
Spot quadratic queue drains and reserveCapacity misuse in review, and replace them with slices, index cursors or a single reservation sized to the data.
Decide when a hot path deserves a dedicated queue or deque structure from a package versus disciplined use of arrays and slices.
## Count, capacity and geometric growth Every `Array` stores its elements in one buffer that can hold more than `count` elements; the size of that buffer is `capacity`. The `Array` documentation describes what happens when you append past it: the array allocates a larger region, copies its elements there, and **the new storage is a multiple of the old storage's size**. Because each reallocation multiplies the room, they get rarer as the array grows, and the cost averages out. The doc comments state the costs precisely: | Member | Documented complexity | |---|---| | `append(_:)` | O(1) on average over many calls on the same array | | `append(contentsOf:)` | O(m) on average, m = number of new elements | | `insert(_:at:)` | O(n); at `endIndex` it is equivalent to `append(_:)` | | `remove(at:)` | O(n) | | `removeFirst()` on an `Array` | O(n) | | `removeLast()` / `popLast()` | O(1) | | `reserveCapacity(_:)` | O(n) | Note the scope of each guarantee: amortized O(1) belongs to `append`, not to `insert(_:at:)`. A single append can be O(n) when it triggers reallocation, or when the buffer is shared with another copy, which forces a copy-on-write first. ## Why the front is expensive An array's elements are contiguous and the first one is always at index `0`. Removing it means moving every remaining element one slot left; inserting at `0` means moving every element one slot right. That is why `remove(at:)` and `insert(_:at:)` are documented as O(n), and why this pattern is quadratic: ```swift while !queue.isEmpty { process(queue.removeFirst()) } ``` For 50,000 thumbnails that is about 1.25 billion element moves. Better shapes: 1. **Walk a slice.** `var rest = queue[...]` gives an `ArraySlice`, and `rest.popFirst()` is O(1) because a slice only advances its `startIndex`. `Array` itself has no `popFirst()`; the compiler rejects it because that method requires a collection that is its own subsequence. 2. **Pop from the back.** If order does not matter, or you reverse once, `popLast()` is O(1). 3. **Keep an index.** Iterate with a cursor and drop the processed prefix in one `removeFirst(k)` call at the end. ## Using reserveCapacity well `reserveCapacity(_:)` guarantees room for at least the requested number of elements, so a loop of appends after it never reallocates until that size is passed. - **Good:** you are about to append a known number of elements, for example building `visible` from 50,000 IDs, so reserve `pendingIDs.count` once before the loop. - **Bad:** calling it repeatedly with a slightly larger number. The `Array` documentation shows `values.reserveCapacity(values.count + 10)` inside a function that runs repeatedly and warns that it causes linear growth, so appends decay to performance linear in `count`. Its advice: remove the call and let `append(_:)` grow the array, or compute your own geometric size. - **Related:** `removeAll(keepingCapacity: true)` empties an array but keeps its buffer for refilling, which avoids reallocating a buffer you are about to fill again. `Dictionary(minimumCapacity:)` and `Set(minimumCapacity:)` play the same role for the hashed collections. ## A review checklist for array-heavy code - A `while` loop around `removeFirst()` or `remove(at: 0)` on a growing array is a quadratic drain; switch to a slice or a cursor. - `insert(_:at: 0)` in a loop builds the array backwards at O(n) per call; append and reverse once at the end instead. - `reserveCapacity(_:)` should appear once, before a loop, with the final size, not inside a function that runs repeatedly. - `removeAll()` followed by refilling a similar number of elements can keep its buffer with `removeAll(keepingCapacity: true)`. - An append that seems slow despite spare capacity may be paying for copy-on-write because another variable shares the buffer. ## How interviewers probe it Expect three moves: "what is the cost of append?" (amortized O(1), explain geometric growth), "what about inserting at the front?" (O(n), and why), and "how would you implement a queue?" A strong answer names the slice or the index cursor and mentions that the standard library's own documentation warns against `reserveCapacity(_:)` in a loop.
- Can a single call to `append(_:)` be O(n)?Yes. When the buffer is full the array reallocates and moves every element, and when the buffer is shared with another copy it must copy before writing. The O(1) guarantee is an average over many appends to the same array.
- Why does `ArraySlice.removeFirst()` run in O(1) while `Array.removeFirst()` is O(n)?A slice is a window with its own `startIndex` over a shared buffer, so removing the first element just moves that index. An array must keep its first element at index 0, so every remaining element shifts.
- Claiming every append is O(1) with no reallocation cost
- Calling reserveCapacity with count plus a few inside a loop
- Using removeFirst() in a loop to drain a large array
- Assuming insert at index 0 is as cheap as append
- Expecting Array to have an O(1) popFirst() method