21.5 · The costs that show up in profiles: collections, strings, formatters, JSON, images and disk
Most slow code is ordinary code doing a lot of an expensive thing: a linear search in a loop, a formatter built a thousand times, a disk write per item. The costs are predictable once you know which operations hide them.
Mental model. Ask of every hot operation: how many times, how big is the input, and does it touch disk, network or the main thread?
In memory
Data-structure, string, formatter, JSON and image costs.
- Which everyday operations are surprisingly expensive in Swift and iOS code, and how do you find and fix them?
The same few costs account for most “it is slow” reports. Linear search in a loop: array.contains is O(n), so calling it for every element of another array is…
On disk
Batching, transactions and write volume.
- How do you reduce disk and database cost: batching writes, transactions, atomic writes, memory mapping and the system’s disk-write limit?
Disk cost is dominated by how many separate operations you issue and whether each one waits for the storage to confirm. Writing one record at a time is far…
More in Performance & energy
- 21.1 · Measure first: the method, the metrics and the noise
- 21.2 · Instruments templates, signposts and XCTMetric
- 21.3 · MetricKit, Organizer and a performance culture
- 21.4 · SwiftUI invalidation and long lists
- 21.6 · Energy: CPU wake-ups, timers, radios, location and thermal state
- 21.7 · App size: thinning, on-demand resources and the binary
- 21.8 · Writing benchmarks you can believe: the optimiser, build settings and growth tests
- 21.9 · Memory you can count: allocations, dirty versus clean pages and decoded images
- 21.10 · The main thread in code: hang watchdogs, actor hops and quality of service
- 21.11 · Launch: lazy initialisation and measuring from process start
- 21.12 · Counting wake-ups: why polling costs energy even when the work is tiny