skip to content

In Swift, what do the -Onone, -O, -Osize and -Ounchecked optimization levels change, and why do you time code only in an optimized build?

level: juniorimportance: should knowfreq 45%

answer

  1. Debug and Release configurations
  2. minimal optimization keeps debugging easy
  3. speed versus binary size
  4. which runtime checks survive
  5. profile what users actually run

basics

~10 s

-Onone barely optimizes so debugging works; -O optimizes for speed, -Osize for smaller code, and -Ounchecked also drops precondition and overflow checks. Debug timings mislead, so profile an -O or -Osize build.

solid answer

~40 s

`-Onone` is what a Debug build uses: the compiler does minimal optimization so breakpoints and variables behave, which leaves calls un-inlined, most generic code unspecialized and extra retain/release traffic in place. `-O` turns the optimizer on with speed as the goal, `-Osize` optimizes with small code size as the goal, and `-Ounchecked` optimizes like `-O` but removes runtime safety checks, so a failing `precondition` no longer traps and integer overflow is no longer caught. `assert` is checked only at `-Onone`. Because abstraction costs that dominate a Debug build often vanish under `-O`, a Debug timing points you at the wrong code; profile the Release configuration, which is what users run.

code

swift · 6 lines
swift
let n = CommandLine.arguments.count        // 1 when run with no arguments
let big = Int.max - 1 + n                  // Int.max, computed at run time

assert(n > 5, "assert fired")              // checked only at -Onone
precondition(n > 5, "precondition fired")  // checked at -Onone and -O
print(big + n)                             // overflow: traps unless -Ounchecked

go deeper

for a junior

Recall the Debug and Release defaults: -Onone for debugging, -O for shipping. Say plainly that you never judge performance from a Debug build.

for a middle

Explain what -Onone leaves in place, such as un-inlined calls, unspecialized generics and extra retain/release, and which of assert, precondition and fatalError still run under -O and -Ounchecked.

for a senior

Show the measuring discipline: profile the Release configuration on a device with real input, compare traces after each change, and treat any speed-up that only shows at -Onone as noise.

for a principal

Frame the level as a team policy: -O or -Osize per target based on measured hot paths and size budgets, -Ounchecked forbidden target-wide, and unchecked arithmetic allowed only locally with review.

## The four optimization levels The Swift compiler, `swiftc`, takes one **optimization level** per build. Xcode exposes it as the Optimization Level build setting; a new project's Debug configuration builds with `-Onone` and its Release configuration with `-O`, and Swift Package Manager does the same for `swift build` and `swift build -c release`. | Flag | `swiftc` describes it as | Typical use | |---|---|---| | `-Onone` | Compile without any optimization | Debug builds, the debugger | | `-O` | Compile with optimizations | Release builds tuned for speed | | `-Osize` | Compile with optimizations and target small code size | Release builds where binary size matters | | `-Ounchecked` | Compile with optimizations and remove runtime safety checks | Rare, isolated hot code | The middle column is the compiler's own `--help` text. Swift's optimization tips note that `-Onone` preserves all debug info, while an optimized build such as `-Osize` can drastically change the emitted code and its debug info is lossy, which is why stepping through a Release build jumps around. ## What -Onone leaves in place At `-Onone` the optimizer barely runs, so the code you wrote is close to the code that executes: - **Calls stay calls.** Small helpers, property accessors and closures passed to `map` or `forEach` are not inlined. - **Generics stay generic.** A generic function mostly runs as one shared body that receives type metadata and witness tables, instead of a copy specialized for `Int` or your struct. - **ARC is literal.** Most retain/release pairs the optimizer would remove are still executed. - **Allocations stay on the heap.** A class instance that never leaves a function is not moved to the stack. None of that is a bug: it is what makes breakpoints, variable inspection and fast incremental builds work. It also means the *relative* cost of code changes between levels. A pipeline of `map`, `filter` and small generic helpers can look like the bottleneck in a Debug trace and then compile to a tight loop under `-O`, while a real algorithmic problem stays slow at every level. ## Which checks survive each level Safety checks are part of the trade. The standard library's `precondition` takes a debug path (print the message, file and line, then trap) and a release path (a bare trap), and the rows below follow the book, the standard library source and a run of the code example with swiftc 6.4: | Check | `-Onone` | `-O` / `-Osize` | `-Ounchecked` | |---|---|---|---| | `assert(_:_:file:line:)` | checked, message printed | not evaluated | not evaluated | | `precondition(_:_:file:line:)` | checked, message printed | checked, traps without your message | not checked; assumed true | | `fatalError(_:file:line:)` | halts | halts | halts | | Integer overflow on `+`, `-`, `*` | traps | traps | check removed | Two consequences matter in practice: 1. Code that relies on `assert` to stop bad input is unprotected in every shipped build; use `precondition` or real error handling for conditions that can happen in production. 2. `-Ounchecked` does not merely make failures quieter. The compiler assumes preconditions hold and optimizes accordingly, so a violated one, or an overflow, becomes wrong behaviour somewhere later instead of a crash at the point of failure. ## Measuring the right build A timing taken at `-Onone` answers the question "how slow is the unoptimized code?", which no user ever runs. To profile a hot path, such as a JSON parser inside your app: 1. Profile the Release configuration. Xcode's Profile action builds Release by default in a new scheme; check the scheme if someone changed it. 2. Use the Time Profiler instrument for where CPU time goes and the Allocations instrument for how many heap allocations the path makes. 3. Profile on the device class your users have, with realistic input sizes, because a debug-sized sample can hide a quadratic cost. 4. Change one thing, rebuild Release, and compare traces; an optimization that only helps `-Onone` is not an optimization. Release builds still produce debug symbols for symbolication, so Instruments can name your functions even though the code is optimized. ## Choosing a level to ship - **`-O`** is the usual Release choice when runtime speed matters most. - **`-Osize`** suits apps or modules where download size or code size dominates; measure the hot paths, because it is allowed to choose smaller code over faster code. - **`-Ounchecked`** is rarely right for a whole target. If a check in one hot loop truly costs, remove that check locally, for example with wrapping operators such as `&+` where wrapping is the intended result, and keep `-O` everywhere else. - Release builds usually also compile the whole module at once, which lets the optimizer see across files; the lesson on method call mechanisms covers what that buys for dispatch.

  • Why does a failing precondition print no message in an -O build, and what should you use when the message must survive?
    In `-O` the standard library's `precondition` takes its release path, a bare conditional trap, so your message, file and line are not printed; the crash report's stack trace is what locates it. `fatalError(_:file:line:)` halts with its message at every optimization level, so use it for unrecoverable states whose explanation you need in the log.
  • Is -Ounchecked a sensible setting for a whole app's Release build?
    Rarely. It only pays where checks sit in hot loops, and in exchange a violated `precondition` or an integer overflow stops crashing and becomes behaviour the optimizer assumed could not happen. Keep `-O` for the target and remove a specific check locally, for example with `&+` where wrapping is correct, after a profile shows that check matters.

  • Timing in a Debug build is fine because the source code is the same.
  • -O strips precondition checks, so Release builds cannot crash on bad input.
  • assert and precondition behave identically in a Release build.
  • -Ounchecked is simply a faster -O with no change in behaviour.
  • The optimization level only changes binary size, never what is slow.