Find An Expensive Copy In A Swift Collection Pipeline

A profile points at a feed transformation. Someone notices result + chunk inside a reduce and proposes replacing every reduce in the project with a loop.

The expression deserves inspection. It does not justify a project-wide rewrite. Swift’s optimizer, the lifetime of intermediate values, and the real element type all affect what work remains at runtime.

Compare equivalent results

Here are three ways to flatten already-materialized chunks. Keep them in a small executable so you can compare outputs before comparing timings:

import Foundation

@inline(never)
func concatenating(_ chunks: [[Int]]) -> [Int] {
    chunks.reduce([]) { result, chunk in result + chunk }
}
@inline(never)
func accumulating(_ chunks: [[Int]]) -> [Int] {
    chunks.reduce(into: []) { result, chunk in result.append(contentsOf: chunk) }
}
@inline(never)
func reserved(_ chunks: [[Int]]) -> [Int] {
    var result: [Int] = []
    let count = chunks.reduce(0) { $0 + $1.count }
    result.reserveCapacity(count)
    for chunk in chunks { result.append(contentsOf: chunk) }
    return result
}

The first form expresses a new concatenated value at each step. The second gives the closure a mutable accumulator. The third also reserves the known final element count once.

Apple’s reduce(into:) documentation recommends that form when the result is a copy-on-write collection. It makes the intended mutation clear. That recommendation does not promise a fixed speedup for every optimized program.

For simple flattening, chunks.flatMap { $0 } is another readable candidate. The point of this fixture is to isolate accumulation behavior, not to declare a universal preferred spelling.

Keep the compiler from measuring nothing

Build with optimization enabled, construct the input outside the timed section, and consume the result afterward. Our fixture checks the entire output against the expected 40,000 integers and prints a checksum.

The @inline(never) annotations make the entry points easier to inspect. They do not turn the executable into a production-grade benchmark or prevent every optimization. Swift’s optimization guidance is useful background for interpreting these experiments.

Run repeated trials, vary input size, and inspect allocations alongside elapsed time. A single cold run includes noise that can be larger than the difference between two fast implementations. Avoid mixing input generation, logging, and result formatting into the interval you attribute to array accumulation.

Reserve once when the size is known

The explicit loop computes a final capacity from arrays whose counts are already cheap to obtain. Do not copy that prepass onto a single-pass sequence that would be consumed or perform work twice.

Also avoid calling reserveCapacity(currentCount + smallIncrement) before every append. Apple’s capacity guidance explains how repeated exact-size reservations can undermine the array’s normal growth strategy.

Reservation is an allocation decision, not a guarantee that later mutations never copy. Another retained value can still share the storage. An array published to a view while the model keeps mutating its own copy has different ownership from a local accumulator used by one function.

Look for the lifetime that keeps storage shared

Copy-on-write preserves value semantics by allowing values to share storage until a mutation needs separation. The expensive event can occur at the mutation, well after the innocent-looking assignment that created another live value.

Check retained snapshots, closure captures, undo history, and bridged Foundation collections near the hot path. A before-and-after UI snapshot may be necessary; removing it solely to eliminate a copy could break the feature’s semantics.

Array value semantics also do not deep-copy arbitrary class instances stored inside the array. Changing a referenced model object is a different operation from replacing an array element. Be clear about which identity and state your optimization is preserving.

Let an uneventful result change the plan

In our first optimized run, all three versions completed in less than a millisecond for the 40,000-integer fixture. There was no dramatic slowdown to report. The reserved version was not the fastest in that single run, which is exactly why a single tiny timing should not choose an architecture.

That result narrows the claim: the sample verifies equivalent collection output and gives us a reproducible place to experiment. It does not establish that the production feed’s bottleneck has been found.

Try the real element type and ownership pattern, then revisit the trace. If decoding, sorting, or repeated UI invalidation dominates, optimize that work instead. Clear mutable accumulation is still a reasonable cleanup; it should not be sold as a measured performance win without evidence.

September 2026 review: the fixture compiled with Swift 6.4 and -O. All three implementations produced identical values and checksums; empty-input checks passed. No allocation trace or device-wide speedup is claimed.