Fix: Swift Array Sorting Runs 100x Slower Than C

Written by

in

Quick answer: A Debug build compiles with -Onone, which keeps every array bounds and integer overflow check and blocks inlining, so sorting a million integers can be far slower than the same code in a Release (-O) build. Re-run the benchmark in Release before changing anything. -Ounchecked (the old -Ofast) removes the safety checks entirely and is not a fix.

Why this happens

Two separate things are going on in that benchmark, and only one of them still matters today.

The first is the optimization level. A Debug build compiles with -Onone: no inlining, no specialization of generic code, no dead-code elimination, and every array bounds check and integer overflow check stays exactly where you wrote it. A Release build compiles with -O. For a tight loop over a million integers, that difference alone is routinely one to two orders of magnitude — and it has nothing to do with sort() specifically.

The second was a real compiler gap in the Swift beta. The optimizer could not prove that the array’s buffer was uniquely referenced, so it emitted swift_retain and swift_release calls around element accesses inside the loop — 26 subroutine calls in the inner loop of the reported assembly. That specific problem is historical. The numbers in the original report (88 s versus 6 s, 443 s versus 0.05 s) come from a pre-1.0 compiler and are not a baseline for anything you build now.

What has not changed is the advice: measure in a Release build first, and do not “fix” performance by switching off the safety checks.

How to fix it

1. Re-run the benchmark in a Release build

Before touching a single line of code, confirm the build configuration.

  • In Xcode: Product > Scheme > Edit Scheme (⌘<) > Run > Build Configuration > Release.
  • In the same pane, untick Debug executable. An attached debugger changes timing and memory behaviour.
  • From the command line, compile with -O instead of the default -Onone.

A minimal, self-contained measurement:

import Foundation

let n = 1_000_000
var values = (0..<n).map { _ in Int.random(in: 0..<n) }

let clock = ContinuousClock()
let elapsed = clock.measure {
    values.sort()
}
print(elapsed)   // e.g. 0.09 seconds

ContinuousClock requires iOS 16 / macOS 13. On older deployment targets use CFAbsoluteTimeGetCurrent() or DispatchTime.now().uptimeNanoseconds around the same call.

Command line, both levels side by side:

xcrun swiftc -O bench.swift -o bench && ./bench
xcrun swiftc -Onone bench.swift -o bench-debug && ./bench-debug

With Swift Package Manager the equivalent is swift build -c release.

2. Know what each optimization level actually does

Level Where it is the default What it does
-Onone Debug No optimization. All checks and all retain/release traffic kept.
-O Release Full optimization. Bounds and overflow checks remain, but the optimizer removes the ones it can prove redundant.
-Osize — Optimizes for binary size. Can be slower than -O in hot loops.
-Ounchecked — -O plus removal of precondition checks: array bounds, integer overflow, precondition. This is what -Ofast was renamed to.

You set it in Build Settings > Swift Compiler – Code Generation > Optimization Level. While you are there, check Compilation Mode: Debug defaults to Incremental, Release to Whole Module. Whole-module compilation lets the optimizer see across files, which matters for generic code like sort().

3. Do not buy speed with -Ounchecked

The original question already found the trap: -Ofast made the code as fast as C++ and simultaneously disabled the checks that make Swift safe. The modern name is -Ounchecked, and it behaves the same way.

let n = 10_000_000
print(n * n * n * n * n)          // traps in -O, undefined behaviour in -Ounchecked

let x = [Int](repeating: 10, count: n)
print(x[n])                        // traps in -O, reads past the buffer in -Ounchecked

In an -O build both lines stop the program with a clear message. In an -Ounchecked build the overflow trap is gone and the out-of-bounds read is undefined behaviour — you get whatever memory follows the buffer, or a crash somewhere unrelated. That is not a performance setting, it is a correctness setting.

If a specific hot loop genuinely needs unchecked arithmetic, isolate it: keep the target at -O and use the &*, &+, &- operators where wrapping is intentional. Those are defined behaviour and do not require disabling checks for the whole module.

4. Reduce the work before changing the compiler

Once you are measuring in Release, the remaining wins are usually algorithmic:

  • Sort value types, not bridged objects. [Int].sort() is a straight buffer of machine integers. Sorting an NSArray of NSNumber, or an array of class instances, adds a message send or a retain/release per comparison.
  • Prefer sort() over sort(by:) with a closure when the element type is Comparable. The closure adds a call per comparison and blocks some specialization.
  • Watch for class references inside hot loops. If a profiler still shows swift_retain/swift_release in a loop that should be pure arithmetic, look for a class instance captured or stored there — that is what keeps the traffic alive today.
  • Reserve capacity when you build the array with append in a loop, so the buffer is not reallocated repeatedly before the sort.

Since Swift 5, sort() and sorted() are stable, so you no longer need a tie-breaking comparator to get deterministic output.

5. Measure with a profiler, not a stopwatch

A single wall-clock number tells you something is slow but not what. Run Instruments > Time Profiler against a Release build, and hide the system libraries so your own frames stay visible. For regression protection, wrap the operation in an XCTest measure { } block — it runs the block repeatedly and reports the standard deviation, so a change that only looks faster shows up as noise.

How to prevent it

  • Benchmark only Release builds; treat Debug timings as meaningless for performance work.
  • Never ship or benchmark with -Ounchecked unless you have audited every arithmetic and indexing operation in the module.
  • Keep Compilation Mode set to Whole Module for Release configurations.
  • Add an XCTest measure { } performance test around any hot path you care about, so a regression fails CI instead of surprising a user.
  • When comparing against C or Python, compare the same algorithm and the same input size — built-in sort() versus a hand-written quicksort is not a language comparison.

FAQ

Is Swift actually slower than C?

Not in any blanket way. For numeric and collection code compiled with -O, Swift lands in the same range as C. The dramatic ratios in the original report came from a beta compiler that emitted retain/release calls inside the loop, and from comparing a -Onone build against an optimized C build.

What replaced -Ofast?

-Ounchecked. It performs the same optimizations as -O but removes precondition checks — array bounds, integer overflow, and precondition — so violations become undefined behaviour instead of a trap. assert is already removed at -O, which is why assertions are for development only.

Why is my app fast in Release but unusable when run from Xcode?

The Run action is almost certainly using the Debug configuration, which means -Onone plus an attached debugger. Switch the scheme’s Run action to Release, or profile with Instruments against a Release build, before concluding that the code itself is slow.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.