Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 146 ยท Advanced Swift

Performance Tips

Write fast Swift: value types and copy-on-write, reserving capacity, generics versus existentials, inlining and @inlinable, lazy sequences, strings, and how to measure.

Swift is designed to be fast by default. It compiles to native code through LLVM, value types live on the stack when they can, and the optimizer is very good at removing abstractions. That is also why performance advice for Swift needs care: most "tips" that were true in one compiler version stop mattering in the next, and guessing at what is slow is how you end up with ugly code that is no faster.

This lesson gives you a mental model of where Swift's costs really come from (heap allocations, copies, reference counting, dynamic dispatch and hidden O(n) operations), shows a few patterns that are reliably worth using, and ends with the most important habit: measure before you change anything. The program on this site is compiled with -O, the same optimized mode a release build uses, so what you see here is close to what production code does.

Order of priority: first pick the right algorithm and data structure (see sorting algorithms and Deque and heap ideas), then remove unnecessary work, and only then think about micro-optimizations. A better algorithm beats any tweak.

Where the time goes

When Swift code is slower than you expected, the cause is almost always one of these five things:

  1. Heap allocation. Classes, closures that escape, arrays, strings beyond 15 bytes and existential boxes allocate. Allocation costs far more than arithmetic.
  2. Copying. Value types are copied on assignment. Small structs are cheap. Large structs, or arrays that are copied because you mutate a shared buffer, are not.
  3. Reference counting. Every retain and release on a class instance is an atomic operation. In a hot loop touching many objects, this adds up. See ARC and deinit.
  4. Dynamic dispatch. Calling a method through a class hierarchy or a protocol existential goes through a table lookup and prevents inlining.
  5. Hidden O(n) work. String.count, array.removeFirst(), array.contains, dictionary.keys.contains, and Array(someLazySequence) inside a loop turn a linear algorithm into a quadratic one without any visible sign.

The rest of the lesson goes through these in order.

Value types and copy-on-write

Arrays, dictionaries, sets and strings are structs, so copying one looks like it must duplicate every element. It does not. The standard collections use copy-on-write (COW): a struct holds a reference to a heap buffer. Assigning the struct copies only the reference. The buffer is duplicated the first time one of the owners mutates it while the buffer is shared.

You can check whether a class instance has exactly one owner with isKnownUniquelyReferenced(&object). That is the whole trick, and you can build your own COW type with it:

Swift Writing a copy-on-write type by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first two add calls do not copy because the IntBag is the only owner. After var second = first two variables point at one Storage, so the first mutation through second copies, and every later one is cheap again. This is exactly what Array does.

What this means for you:

  • Passing an array to a function is free. Do not reach for inout or classes "to avoid copying".
  • Mutating a shared array is the expensive step. If you keep an extra reference to an array (stored in a property, captured by a closure) and then mutate the original in a loop, you can trigger a full copy on the first mutation.
  • Avoid mutating through a copy in a loop. var copy = items; copy.append(x) inside a loop is a full O(n) copy each time if items is still alive.

Large structs full of arrays are still cheap to copy, because they copy references. A struct with a hundred Int fields is expensive to copy (800 bytes each time); consider storing those in an array or a class instead.

Reserve capacity and avoid repeated growth

An array grows by allocating a bigger buffer and moving the elements, which makes append amortized O(1) but not free: while you add a million elements the array reallocates about 20 times. If you know the size in advance, say so:

Swift reserveCapacity and building arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

map, filter, Array(repeating:count:) and Array(unsafeUninitializedCapacity:) all allocate once. Prefer them to a manual loop that starts from [] when they say the same thing.

Strings: the hidden costs

String is a collection of characters (extended grapheme clusters), so it cannot jump to the nth character without walking the text. That makes these operations O(n):

  • text.count
  • text[text.index(text.startIndex, offsetBy: n)]
  • anything that uses characters.count in a loop condition

When you only need bytes or code units, the other views are much cheaper: text.utf8.count is O(1) for native strings.

Swift Counting, views and substrings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Two pitfalls professionals watch for:

  • Keeping a Substring alive keeps the whole original string alive. Convert with String(sub) when you store it long term.
  • Looping with an Int index into a String is quadratic. If you need random access, convert once with Array(text) and index the array, or work with text.utf8 or unicodeScalars when the data is known to be ASCII.

Generics versus existentials

A generic function such as func total<S: Shape>(_ s: S) is specialized by the compiler: it creates a copy of the function for each concrete type used, and every call inside is direct and can be inlined. A function taking any Shape receives a box that holds the value (inline if it fits in three words, otherwise on the heap) plus a pointer to the witness table, and calls go through that table.

Swift Boxes versus generics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

[Square] stores 8-byte squares one after another. [any Shape] stores 40-byte boxes, and a big value would add a heap allocation per element. Use any when you truly need a mix of types in one collection, and use generics or some everywhere else. See Opaque types and Protocols.

When you use a protocol with an associated type as a type (any Container), the compiler no longer knows what Item is, so it erases it to Any. Code that expects the real type fails to compile:

Swift Associated types are erased behind any (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The compiler says error: cannot convert value of type 'Any' to specified type 'Int'. The fix is to stay generic (func firstItem<C: Container>(_ c: C) -> C.Item?) so the item type survives, and to keep any for places where you really do not care about it.

Classes, final and dispatch

A method on a non-final class may be overridden, so a call must be dispatched through the class's vtable. When the compiler can prove no override exists it still devirtualizes the call, and with whole-module optimization (the default for release builds in SwiftPM and Xcode, and the mode used for this lesson's programs) it can often see the whole module. You help it by:

  • marking classes final unless they are designed for inheritance;
  • marking members private or fileprivate when they are, because the compiler then knows every use;
  • preferring structs and enums with protocols over class hierarchies (see Value vs reference).

Do not mark everything final and private "for speed" and then discover later that you cannot test or extend it. Do it where the design already says "this is not meant to be overridden".

Inlining across modules: @inlinable

Inside one module the optimizer can inline anything. Across a module boundary (a library you ship to others) the compiler normally sees only the signature, so a tiny generic function in a library cannot be specialized for your types. Two attributes change that. This is a read-only example because it needs a separate library module:

Swift
// In the library module "Geometry"
@frozen public struct Point {
    public var x: Double
    public var y: Double
}

@inlinable
public func distanceSquared(_ a: Point, _ b: Point) -> Double {
    let dx = a.x - b.x
    let dy = a.y - b.y
    return dx * dx + dy * dy
}

@inlinable publishes the function body so callers can inline and specialize it. The price is that the body becomes part of your library's public contract: it can only use public or @usableFromInline declarations, and changing it later does not change binaries compiled against the old version. @frozen promises that a struct's stored properties will never change, which lets clients lay it out directly. Use these for hot, small, stable code in libraries; do not use them in an application.

Lazy sequences and doing less work

map and filter on an array produce a new array immediately. If you only need the first few results, or you chain several steps, a lazy sequence does the work on demand and allocates no intermediate arrays:

Swift Eager versus lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The eager chain computes all 1,000 squares before you look at three of them; the lazy chain computes exactly 21, because the third square divisible by 7 is 21 squared and the loop stops there. More in Lazy sequences. Also prefer first(where:) and contains over building a filtered array just to look at one element, and use a Set for repeated membership tests.

Measure, do not guess

Intuition about speed is unreliable. Use these tools in this order:

  1. A quick benchmark. ContinuousClock measures elapsed time. Run the work several times, use a result so the optimizer cannot delete it, and compare variants on the same machine.
  2. Instruments (Time Profiler, Allocations) on Apple platforms, or perf and valgrind --tool=callgrind on Linux, to see where the time and allocations are.
  3. swift-collections-benchmark or package-benchmark (read-only, third-party packages) for repeatable comparisons.
Swift A small benchmark helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Rules of thumb for benchmarking: use release mode (-O), never time a single run, make sure the result is used, and compare relative differences rather than absolute numbers.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does copy-on-write mean for an Array?

    Assignment copies a reference to the buffer. The first mutation of a buffer that has more than one owner makes a private copy.
  2. 2. Which operation is O(n) on a String?

    String.count counts extended grapheme clusters, so it has to walk the text. The utf8 count is stored, and isEmpty and startIndex are constant time.
  3. 3. Why is [any Shape] usually slower than [Square]?

    An existential carries extra storage and goes through a witness table. Concrete elements are stored inline and calls can be inlined.
  4. 4. What does @inlinable do on a public function of a library?

    The body becomes visible to other modules, which allows cross-module inlining and specialization at the price of a stricter compatibility contract.
  5. 5. What should you do before optimizing a slow function?

    Guessing leads to complicated code that may not help. Measure in release mode, find the actual bottleneck, then change one thing and measure again.

Summary

  • The usual costs are heap allocation, copying, reference counting, dynamic dispatch and hidden O(n) operations; choose algorithms first.
  • Collections are value types with copy-on-write: assignment is cheap, mutating a shared buffer copies it. isKnownUniquelyReferenced lets you build your own COW types.
  • reserveCapacity, map and friends avoid repeated reallocation.
  • String.count is linear; use utf8 views for byte work and String(substring) before storing a Substring.
  • Prefer generics and some to any; use any when you need a heterogeneous collection. Protocols with associated types need any when used as a type.
  • Use final, private and whole-module optimization to help devirtualization; use @inlinable and @frozen only in libraries, deliberately.
  • Lazy sequences do work on demand; measure with ContinuousClock in release mode and profile before optimizing.

Next: Testing in Swift