Arrays from scratch
How an array list works: constant-time indexing, fixed storage and its invariants, resizing by a factor and why it makes adding fast on average, clearing references, subscripts, circular arrays, and raw memory underneath Swift’s Array.
- Swift book
- Subscripts · Memory Safety
- Documentation
- ManagedBuffer · UnsafeMutableBufferPointer · Array
A linked list reaches its ends in constant time, but its middle only by
walking. An array is the opposite kind of structure: every position is
reachable in one step. This lesson builds CS61B’s AList, a list stored in
an array, and the two tricks that make it the right default for almost
everything: resizing and circular indexing. Swift’s own Array is
built the same way.
Why indexing is instant
An array stores its items in one contiguous block of memory. If each item
takes 8 bytes and the block starts at address a, then item i is at
address a + 8 × i. Finding it is one multiplication and one addition,
whether i is 3 or 3 million. A linked list has no such formula: item i
is wherever the previous node says.
Contiguous storage has a second advantage, which is often bigger in practice. Processors read memory in chunks and keep recently read chunks in fast caches, so reading neighboring items is much cheaper than jumping around. Adding up a million integers took about 0.16 milliseconds in an array and about 6.3 in a linked list on the machine this lesson was written on: roughly 40 times slower, for the same number of steps. Linked nodes are also separate allocations, each with its own header and reference count. That is why Swift’s standard library has no linked list at all.
An AList with fixed storage
Our list stores items in a Swift array used only as a block of slots: we
create it at a fixed size and never call append or remove on it. Unused
slots hold nil. This is the Swift counterpart of Java’s new Item[100],
which is filled with null:
struct AList<Element> {
private var items = [Element?](repeating: nil, count: 100)
private(set) var count = 0
mutating func addLast(_ item: Element) {
items[count] = item
count += 1
}
func get(_ index: Int) -> Element {
precondition((0..<count).contains(index), "index \(index) out of range")
return items[index]!
}
var last: Element? {
count > 0 ? items[count - 1] : nil
}
mutating func removeLast() -> Element? {
guard count > 0 else {
return nil
}
count -= 1
let item = items[count]
items[count] = nil
return item
}
}
var list = AList<String>()
list.addLast("a")
list.addLast("b")
list.addLast("c")
print(list.get(1), list.removeLast()!, list.count, list.last!) // b c 2 b
The code rests on three invariants, which CS61B lists explicitly:
- The next item to add goes at position
count. - The number of items is
count. - The last item is at position
count - 1.
Every method relies on them and preserves them. removeLast does not even
need to erase anything to keep them true; it erases the slot for a different
reason, below.
Resizing
The list above holds at most 100 items. When it is full, the only option is to get a bigger block and copy everything into it. The question is how much bigger.
var copies = 0
func fill(_ n: Int, grow: (Int) -> Int) -> Int {
copies = 0
var capacity = 1
var count = 0
for _ in 0..<n {
if count == capacity {
copies += count // copy every item into the new block
capacity = grow(capacity)
}
count += 1
}
return copies
}
print(fill(10_000) { $0 + 1 }) // 49995000
print(fill(10_000) { $0 * 2 }) // 16383
Growing by one slot at a time copies the whole list on every add: 1 + 2 + 3 + … + 9,999 copies, nearly 50 million for ten thousand items. The work grows with the square of the size. Doubling copies 1 + 2 + 4 + … + 8,192, which is 16,383, less than two copies per item. However many items are added, the total copying stays under twice the number of items.
That is the key idea of an array list: an occasional add is expensive, but
averaged over all adds, each costs a constant amount. This is called
amortized constant time, and Lesson 37 analyzes it properly. Any
multiplicative factor works; Swift’s Array also doubles, while other
libraries use 1.5 to waste less memory.
What would Swift print?
var capacity = 4
var resizes = 0
for count in 0..<50 {
if count == capacity {
capacity *= 2
resizes += 1
}
}
print(capacity, resizes)Show answer and explanation
Answer64 4
Capacity doubles when the 5th, 9th, 17th, and 33rd items arrive: 4, 8, 16, 32, 64. Fifty items need only four resizes, and a million would need about eighteen.
Swift’s Array reports its current block size as capacity, and
reserveCapacity(_:) grows it in advance when you know how many items are
coming, which skips the intermediate copies entirely.
Shrinking, and letting go
Two memory questions remain. First, if a list grows to a million items and then shrinks to ten, it still holds a block of a million slots. CS61B’s rule is to halve the block when it becomes less than a quarter full. Halving at one half would be a mistake: a list sitting right at the boundary could double and halve on alternate operations, copying everything every time.
Second, removeLast sets the vacated slot to nil. The invariants do not
need it, but ARC does. If the slot still referred to the removed object, that
object could never be freed while the list lived, even though no one could
ever reach it through the list. Java programmers call this loitering. In
Swift, clearing the slot releases the reference, and the object is freed as
soon as nothing else holds it.
Subscripts
list.get(1) works, but Swift collections are indexed with brackets. A
subscript declares what brackets mean for a type, with a getter and,
optionally, a setter:
struct AList<Element> {
private var items = [Element?](repeating: nil, count: 8)
private(set) var count = 0
mutating func addLast(_ item: Element) {
if count == items.count {
resize(to: items.count * 2)
}
items[count] = item
count += 1
}
subscript(index: Int) -> Element {
get {
precondition((0..<count).contains(index), "index \(index) out of range")
return items[index]!
}
set {
precondition((0..<count).contains(index), "index \(index) out of range")
items[index] = newValue
}
}
private mutating func resize(to capacity: Int) {
var bigger = [Element?](repeating: nil, count: capacity)
for i in 0..<count {
bigger[i] = items[i]
}
items = bigger
}
}
var squares = AList<Int>()
for n in 1...20 {
squares.addLast(n * n)
}
squares[0] = -1
print(squares[0], squares[19], squares.count) // -1 400 20
A subscript can take any parameters, several at once, and even labels:
matrix[row: 2, column: 3] is a subscript with two labeled parameters. The
Swift book’s chapter on subscripts covers the options.
Circular arrays
An AList is fast at the back but slow at the front: addFirst must shift
every item one slot to the right. The fix is the ring buffer from Lesson
27’s tests. Let the front be anywhere. Store the index where the first item
is, and compute every position modulo the capacity, so the items can wrap
around the end of the block:
capacity 8, first = 6, count = 4
index: 0 1 2 3 4 5 6 7
[ c ][ d ][ ][ ][ ][ ][ a ][ b ]
▲ first
The items, in order, are a, b, c, d. Item i is at position
(first + i) % capacity. Adding at the front moves first one step back,
wrapping from 0 to 7; adding at the back writes at (first + count) % capacity.
Both are constant time, so a circular array is a deque, which is Project 7.
CS61B’s version tracks nextFirst and nextLast, the positions where the
next items at each end will go, rather than first and count. The two
designs are equivalent; choose one, write down its invariants, and never mix
them.
What would Swift print?
let capacity = 8
var first = 0
var positions: [Int] = []
for _ in 0..<3 {
first = (first - 1 + capacity) % capacity
positions.append(first)
}
print(positions, (first + 5) % capacity)Show answer and explanation
Answer[7, 6, 5] 2
Each addFirst steps first back, wrapping from 0 to 7. With first at 5,
item 5 is at (5 + 5) % 8 = 2. Adding capacity before % avoids a negative
remainder, since -1 % 8 is -1 in Swift.
Resizing a circular array cannot copy slot i to slot i: the items would
keep their wrapped-around layout in a block of a different size, and the
formula would break. Instead, copy item i (at (first + i) % oldCapacity)
to position i of the new block, and set first to 0. Lesson 27’s bug was
exactly this.
All the way down: raw memory
Our AList stores Element? in a Swift array. Swift’s real Array cannot
be built on itself; underneath, it manages raw memory: a block allocated
for a given number of elements, some of which are initialized (contain
a real value) and some not. Swift’s memory-safety rules usually make
uninitialized memory impossible to touch, but the standard library exposes
it through types marked unsafe, for building exactly this kind of
structure:
final class RawList<Element> {
private var storage: UnsafeMutablePointer<Element>
private var capacity: Int
private(set) var count = 0
init(capacity: Int = 4) {
self.capacity = capacity
storage = .allocate(capacity: capacity) // uninitialized
}
deinit {
storage.deinitialize(count: count) // destroy the items
storage.deallocate() // return the block
}
func append(_ item: Element) {
if count == capacity {
let bigger = UnsafeMutablePointer<Element>.allocate(capacity: capacity * 2)
bigger.moveInitialize(from: storage, count: count) // move, do not copy
storage.deallocate()
storage = bigger
capacity *= 2
}
(storage + count).initialize(to: item)
count += 1
}
func removeLast() -> Element? {
guard count > 0 else {
return nil
}
count -= 1
return (storage + count).move() // the slot is uninitialized again
}
subscript(index: Int) -> Element {
precondition((0..<count).contains(index), "index \(index) out of range")
return storage[index]
}
}
let raw = RawList<String>()
for word in ["one", "two", "three", "four", "five"] {
raw.append(word)
}
print(raw[4], raw.removeLast()!, raw.count) // five five 4
Every slot is in one of two states, and each operation must know which:
allocategives uninitialized memory;initialize(to:)puts a value in an uninitialized slot. Assigning to an uninitialized slot would try to release an old value that is not there.move()takes the value out and leaves the slot uninitialized;moveInitialize(from:count:)does that for a whole range, relocating items to the new block without copying and releasing each one.deinitmustdeinitializeexactly the initialized slots, releasing the items, and thendeallocatethe block. Forget the first and the items leak; do it twice and the program crashes, or worse, silently corrupts memory.
The Swift book’s chapter on memory safety explains the rules the compiler
enforces in ordinary code. Unsafe pointers switch those checks off, which
is why real collections wrap them in a small, carefully tested type and
expose only a safe interface, as RawList does. ManagedBuffer, which
Swift’s own collections use, puts the count and the elements in a single
allocation, but follows the same rules.
Put the lines in order
Put the lines in order so the program prints [c, a, b].
first = (first - 1 + 3) % 3var ring: [String?] = ["a", "b", nil], first = 0print("[" + items.joined(separator: ", ") + "]")ring[first] = "c"let items = (0..<3).map { ring[(first + $0) % 3]! }
Show the correct program
var ring: [String?] = ["a", "b", nil], first = 0
first = (first - 1 + 3) % 3
ring[first] = "c"
let items = (0..<3).map { ring[(first + $0) % 3]! }
print("[" + items.joined(separator: ", ") + "]")Lab 29: Array lists
Q0: What would Swift print?
What would Swift print?
final class Tracked {
static var alive = 0
init() { Tracked.alive += 1 }
deinit { Tracked.alive -= 1 }
}
var slots: [Tracked?] = [Tracked(), Tracked(), nil]
var count = 2
count -= 1
print(Tracked.alive)
slots[count] = nil
print(Tracked.alive)Show answer and explanation
Answer2
1
Decreasing count removes the item as far as the list is concerned, but the
slot still refers to the object, so it stays alive: loitering. Clearing the
slot releases it.
What would Swift print?
var copies = 0
var capacity = 1
for count in 0..<100 {
if count == capacity {
copies += count
capacity += 10
}
}
print(copies)Show answer and explanation
Answer460
Growing by 10 slots at a time resizes when the count reaches 1, 11, 21, …, 91, copying that many items each time: 1 + 11 + 21 + … + 91 = 460. Adding a constant number of slots still makes the total copying grow with the square of the size, only more slowly than adding one.
Q1: A resizing AList
Write AList<Element> with addLast, removeLast, count, a subscript,
and capacity (the size of its storage), starting at 8 slots and doubling
when full. Clear vacated slots. Test it against [Element] with random
operations, and check that capacity is always a power of two at least as
large as count.
Show solution
struct AList<Element> {
private var items = [Element?](repeating: nil, count: 8)
private(set) var count = 0
var capacity: Int { items.count }
mutating func addLast(_ item: Element) {
if count == items.count {
resize(to: items.count * 2)
}
items[count] = item
count += 1
}
mutating func removeLast() -> Element? {
guard count > 0 else {
return nil
}
count -= 1
defer { items[count] = nil }
return items[count]
}
subscript(index: Int) -> Element {
get {
precondition((0..<count).contains(index))
return items[index]!
}
set {
precondition((0..<count).contains(index))
items[index] = newValue
}
}
private mutating func resize(to capacity: Int) {
var bigger = [Element?](repeating: nil, count: capacity)
for i in 0..<count {
bigger[i] = items[i]
}
items = bigger
}
}
var list = AList<Int>()
var reference: [Int] = []
var random = SystemRandomNumberGenerator()
for n in 0..<5_000 {
if Int.random(in: 0..<3, using: &random) < 2 {
list.addLast(n)
reference.append(n)
} else {
assert(list.removeLast() == reference.popLast())
}
assert(list.count == reference.count)
assert(list.capacity >= list.count && list.capacity.nonzeroBitCount == 1)
if let i = reference.indices.randomElement(using: &random) {
assert(list[i] == reference[i])
}
}nonzeroBitCount == 1 is a quick test for a power of two: in binary, a power
of two has exactly one bit set. The defer clears the slot after its value
has been read for the return.
Q2: Shrinking
Extend AList so that removeLast halves the storage when fewer than a
quarter of the slots are in use, but never below 8 slots. Show with a test
that adding a million items and then removing all but ten leaves a small
capacity, and that alternating adds and removes at a boundary does not
resize every time.
Show solution
struct AList<Element> {
private var items = [Element?](repeating: nil, count: 8)
private(set) var count = 0
private(set) var resizes = 0
var capacity: Int { items.count }
mutating func addLast(_ item: Element) {
if count == items.count {
resize(to: items.count * 2)
}
items[count] = item
count += 1
}
mutating func removeLast() -> Element? {
guard count > 0 else {
return nil
}
count -= 1
let item = items[count]
items[count] = nil
if items.count > 8 && count < items.count / 4 {
resize(to: items.count / 2)
}
return item
}
private mutating func resize(to capacity: Int) {
var resized = [Element?](repeating: nil, count: capacity)
for i in 0..<count {
resized[i] = items[i]
}
items = resized
resizes += 1
}
}
var big = AList<Int>()
for n in 0..<1_000_000 {
big.addLast(n)
}
while big.count > 10 {
_ = big.removeLast()
}
assert(big.capacity <= 64)
var edge = AList<Int>()
for n in 0..<16 {
edge.addLast(n) // exactly full at 16
}
let before = edge.resizes
for n in 0..<1_000 {
edge.addLast(n) // grows to 32 once
_ = edge.removeLast() // 16 of 32 is not below a quarter: no shrink
}
assert(edge.resizes == before + 1)After a halving, the list is still at most half full, so it takes many more operations in either direction before the next resize: the cost of each resize is spread over the operations since the last one. Shrinking at one half instead would make the boundary test resize on every single operation.
Q3: Insert and remove in the middle
Add insert(_:at:) and remove(at:) to AList, shifting items as needed.
How many items does each move, in the worst case?
Show solution
struct AList<Element> {
private var items = [Element?](repeating: nil, count: 8)
private(set) var count = 0
mutating func insert(_ item: Element, at index: Int) {
precondition((0...count).contains(index))
if count == items.count {
var bigger = [Element?](repeating: nil, count: items.count * 2)
for i in 0..<count {
bigger[i] = items[i]
}
items = bigger
}
var i = count
while i > index { // shift right, starting from the end
items[i] = items[i - 1]
i -= 1
}
items[index] = item
count += 1
}
mutating func remove(at index: Int) -> Element {
precondition((0..<count).contains(index))
let item = items[index]!
for i in index..<(count - 1) { // shift left, starting from the gap
items[i] = items[i + 1]
}
count -= 1
items[count] = nil
return item
}
var toArray: [Element] {
(0..<count).map { items[$0]! }
}
}
var list = AList<String>()
for (i, word) in ["b", "d", "a", "c", "e"].enumerated() {
list.insert(word, at: [0, 1, 0, 2, 4][i])
}
assert(list.toArray == ["a", "b", "c", "d", "e"])
assert(list.remove(at: 0) == "a" && list.remove(at: 3) == "e")
assert(list.toArray == ["b", "c", "d"])Both move every item after the index, so inserting or removing at the front
moves all count items: linear time. The shifting direction matters. Shifting
right must start from the end, or each item would overwrite the next before
it moved.
Q4: Reading a circular array
Given the storage, first, and count of a circular array, write
items(_:first:count:), returning the items in order, and
physicalIndex(of:first:capacity:), returning where item i is stored.
Show solution
func physicalIndex(of i: Int, first: Int, capacity: Int) -> Int {
(first + i) % capacity
}
func items<T>(_ storage: [T?], first: Int, count: Int) -> [T] {
(0..<count).map { storage[physicalIndex(of: $0, first: first, capacity: storage.count)]! }
}
let storage: [String?] = ["c", "d", nil, nil, nil, nil, "a", "b"]
assert(items(storage, first: 6, count: 4) == ["a", "b", "c", "d"])
assert(physicalIndex(of: 3, first: 6, capacity: 8) == 1)
assert(items(storage, first: 0, count: 2) == ["c", "d"])Q5: Resizing a circular array
Write CircularBuffer<Element> with addFirst, addLast, removeFirst,
removeLast, and toArray, starting at capacity 4 and doubling when full,
by unrolling the items into the new storage starting at position 0. Test it
against [Element] with random operations. This is most of Project 7.
Show solution
struct CircularBuffer<Element> {
private var items = [Element?](repeating: nil, count: 4)
private var first = 0
private(set) var count = 0
private func position(_ i: Int) -> Int {
(first + i) % items.count
}
mutating func addFirst(_ item: Element) {
growIfFull()
first = (first - 1 + items.count) % items.count
items[first] = item
count += 1
}
mutating func addLast(_ item: Element) {
growIfFull()
items[position(count)] = item
count += 1
}
mutating func removeFirst() -> Element? {
guard count > 0 else { return nil }
let item = items[first]
items[first] = nil
first = (first + 1) % items.count
count -= 1
return item
}
mutating func removeLast() -> Element? {
guard count > 0 else { return nil }
let last = position(count - 1)
let item = items[last]
items[last] = nil
count -= 1
return item
}
var toArray: [Element] {
(0..<count).map { items[position($0)]! }
}
private mutating func growIfFull() {
guard count == items.count else { return }
var bigger = [Element?](repeating: nil, count: items.count * 2)
for i in 0..<count {
bigger[i] = items[position(i)]
}
items = bigger
first = 0
}
}
var buffer = CircularBuffer<Int>()
var reference: [Int] = []
var random = SystemRandomNumberGenerator()
for n in 0..<10_000 {
switch Int.random(in: 0..<4, using: &random) {
case 0:
buffer.addFirst(n)
reference.insert(n, at: 0)
case 1:
buffer.addLast(n)
reference.append(n)
case 2:
assert(buffer.removeFirst() == (reference.isEmpty ? nil : reference.removeFirst()))
default:
assert(buffer.removeLast() == reference.popLast())
}
assert(buffer.count == reference.count)
}
assert(buffer.toArray == reference)growIfFull must run before addFirst moves first: afterwards, the new
item’s slot would already be computed for the old capacity.
Q6 (optional): Leak-free raw memory
Add removeAll() and a settable subscript to RawList, and test it with a
class whose instances count themselves, checking that every item is freed
exactly once: after removals, after removeAll(), and when the list itself is
freed.
Show solution
final class Tracked {
static var alive = 0
let id: Int
init(_ id: Int) {
self.id = id
Tracked.alive += 1
}
deinit {
Tracked.alive -= 1
}
}
final class RawList<Element> {
private var storage: UnsafeMutablePointer<Element>
private var capacity: Int
private(set) var count = 0
init(capacity: Int = 4) {
self.capacity = capacity
storage = .allocate(capacity: capacity)
}
deinit {
storage.deinitialize(count: count)
storage.deallocate()
}
func append(_ item: Element) {
if count == capacity {
let bigger = UnsafeMutablePointer<Element>.allocate(capacity: capacity * 2)
bigger.moveInitialize(from: storage, count: count)
storage.deallocate()
storage = bigger
capacity *= 2
}
(storage + count).initialize(to: item)
count += 1
}
func removeLast() -> Element? {
guard count > 0 else { return nil }
count -= 1
return (storage + count).move()
}
func removeAll() {
storage.deinitialize(count: count)
count = 0
}
subscript(index: Int) -> Element {
get {
precondition((0..<count).contains(index))
return storage[index]
}
set {
precondition((0..<count).contains(index))
storage[index] = newValue // an initialized slot: assignment releases the old value
}
}
}
var list: RawList<Tracked>? = RawList()
for n in 0..<10 {
list!.append(Tracked(n))
}
assert(Tracked.alive == 10)
_ = list!.removeLast()
list![0] = Tracked(99) // replaces item 0, which is freed
assert(Tracked.alive == 9 && list![0].id == 99)
list!.removeAll()
assert(Tracked.alive == 0 && list!.count == 0)
for n in 0..<5 {
list!.append(Tracked(n))
}
list = nil
assert(Tracked.alive == 0)The setter can use plain assignment because slot index is initialized, and
assignment to initialized memory releases the old value. removeAll keeps
the block for reuse, like Swift’s removeAll(keepingCapacity: true).
What’s next
We now have two very different deques with the same operations. Next lesson: interfaces and inheritance, and how to write code that works with either.