Sub topic 14
Release builds: codegen units, LTO and opt-level
This chapter assumes you can read a Cargo.toml, know the difference between cargo build and cargo build --release, and have read the earlier chapters on the compile pipeline and measuring builds. Here you will tune the settings that decide how hard LLVM works on your code. These settings trade build time for runtime speed, so there is no free option. The aim is to pick the right trade for each kind of build.
Why release builds are slow
A dev build asks LLVM for almost no optimization (opt-level = 0). A release build asks for a lot. LLVM then runs many passes: inlining, loop transformations, vectorization, and dead-code removal. These passes cost far more time than parsing and type checking in rustc.
Three settings control most of this cost:
opt-levelsets how many optimization passes LLVM runs.codegen-unitssets how many pieces a crate is split into for LLVM, which affects both parallelism and optimization quality.ltosets whether LLVM can optimize across crate boundaries.
Release builds also skip incremental compilation by default, so a small edit usually recompiles whole crates.
opt-level
opt-level accepts these values:
| Value | Meaning | Typical use |
|---|---|---|
| `0` | No optimization | Dev builds (default) |
| `1` | Basic optimization | Fast builds that still run acceptably |
| `2` | Most optimizations | Good balance |
| `3` | All of `2`, plus more aggressive inlining and vectorization | Release default |
| `"s"` | Optimize for small binary size | Embedded, WebAssembly |
| `"z"` | Optimize for size even more, and disable loop vectorization | Strictest size limits |
Notice that "s" and "z" are strings in TOML, while the numeric levels are integers. Going from 3 to 2 often saves some compile time and costs little runtime speed, but the effect depends on the code. 3 is not always faster at runtime than 2, because more aggressive inlining can bloat code and hurt the instruction cache. Measure with your real workload.
codegen-units
rustc splits each crate into codegen units (CGUs) and hands them to LLVM, which can optimize them in parallel. The release default is 16. Dev builds use 256 with incremental compilation, so a small change only touches a few units.
- More CGUs means more parallelism and faster builds. LLVM sees less of the crate at once, so it inlines less across unit boundaries and the binary can be slower.
codegen-units = 1gives LLVM the whole crate at once. This is the best optimization and the slowest build, because that work runs on one thread.
If your machine has many cores but one crate dominates the timeline in cargo build --timings, a higher CGU count can use idle cores. Check this by looking at whether the long bar for that crate shows a single busy thread.
Link-time optimization
Without LTO, each crate is optimized on its own. A function in a dependency can only be inlined into your code if it is marked #[inline] or is generic. LTO keeps the LLVM bitcode (the compiler's intermediate form) of all crates and optimizes them together at link time.
| `lto` value | Behavior | Cost |
|---|---|---|
| `false` (default) | "Thin local" LTO: only across CGUs within each crate | Low |
| `"off"` | No LTO at all, not even between CGUs | Lowest |
| `"thin"` | ThinLTO across all crates, run in parallel | Medium |
| `true` or `"fat"` | All crates merged into one module | High, mostly single-threaded |
ThinLTO usually recovers most of the speedup that fat LTO gives, and it costs much less time. Try "thin" first. Move to "fat" only if benchmarks show a gain you need.
One more detail: LTO works best with codegen-units = 1, but it does not require it. Fat LTO already merges everything, so the CGU setting matters less for the final link step. It still affects the per-crate optimization before the merge.
Other settings that affect release time
panic = "abort"removes unwinding tables and landing pads. This shrinks the binary and gives LLVM less to work on. It changes behavior, because panics can no longer be caught withcatch_unwindand destructors do not run on panic. Tests need unwinding, so Cargo ignores this setting for the test profile.debugcontrols debug info. The release default isfalse. If you turn it on for profiling,"line-tables-only"costs much less than full debug info.strip = "symbols"removes symbols from the final binary. This makes the file smaller and slightly speeds up the link, but backtraces lose function names.incremental = truecan be enabled in a release-like profile for faster rebuilds, at some cost in runtime speed. It is not meant for builds you ship.
A practical layout: release and dist profiles
You do not have to pick one set of values. Cargo supports custom profiles that inherit from a built-in one. A common pattern is to keep release moderate for everyday use, and add a separate profile for the artifacts you publish.
# Cargo.toml (workspace root)
[workspace]
resolver = "2"
members = ["app", "core"]
# Everyday release builds: reasonable speed, quick to build.
[profile.release]
opt-level = 2
lto = "off"
codegen-units = 16
debug = "line-tables-only"
# Third-party code rarely changes; optimize it fully.
[profile.release.package."*"]
opt-level = 3
# Final artifacts: slow to build, fastest and smallest to run.
[profile.dist]
inherits = "release"
opt-level = 3
lto = "fat"
codegen-units = 1
panic = "abort"
strip = "symbols"
debug = falseBuild with the custom profile like this:
cargo build --release
cargo build --profile distCargo puts output for a custom profile in target/dist/, not target/release/. Profiles are only read from the workspace root Cargo.toml. Profile sections in member crates are ignored, and Cargo warns about them.
Two cautions apply to this example. First, panic = "abort" in dist means the binary behaves differently from the one you tested in release. Run your test suite against the configuration you ship, or drop the setting. Second, a per-package override such as [profile.release.package."*"] only affects dependencies. Your workspace members keep the profile's top-level values.
Build scripts and proc macros
Build scripts and procedural macros are compiled for the host machine and run during the build. Cargo compiles them using the build-override section, whose default is opt-level = 0 with no debug info. This is usually right, because they run once. If a heavy proc macro or build script (for example, one that parses a large schema) dominates your timeline, raising its opt-level can help:
[profile.release.build-override]
opt-level = 2Test this before keeping it. Optimizing the macro's crates costs compile time too, and it pays off only if the macro runs long enough.
Choosing settings: a decision flow
Measuring the effect
Do not guess. Compare builds on the same machine and change one setting at a time. Use cargo build --timings with each profile and read the total time and the long bars for the final crates. Time a clean build (cargo clean first) and a rebuild after a one-line change, because they behave differently. Then run a benchmark that matches your real workload. A microbenchmark can mislead you about which setting is worth its build cost.
Also check binary size with ls -l target/dist/yourapp. Size is a side benefit of panic = "abort", strip, and opt-level = "s", and it can matter even when speed does not.
Common errors
- Setting
[profile.release]in a member crate'sCargo.tomland seeing no effect. Move it to the workspace root. - Writing
opt-level = swithout quotes. TOML rejects it, so writeopt-level = "s". - Using
lto = "fat"withcodegen-units = 1for every CI run, then wondering why CI takes ten minutes longer. Reserve this combination for the dist build. - Comparing timings after only a warm rebuild. Incremental state and cached dependencies can hide the real cost.
- Expecting
panic = "abort"to apply tocargo test. It does not, because the test harness needs unwinding.
Exercises
Exercise
A workspace's CI builds take 14 minutes using lto = "fat" and codegen-units = 1. Benchmarks show the CI binary only needs to be roughly as fast as production for smoke tests. Which two changes would you try first, and what do you give up?
Show answer
Switch lto to "thin" and raise codegen-units back to 16 (or move the fat/1 combination to a separate dist profile used only for releases). ThinLTO runs in parallel and CGUs spread work over several cores, so the build gets shorter. You give up some cross-crate and cross-unit inlining, so the binary can be a few percent slower. Verify with cargo build --timings and a benchmark.
Exercise
You add [profile.release] lto = "thin" to crates/core/Cargo.toml in a workspace, and the build is unchanged. Why, and how do you fix it?
Show answer
Cargo reads profile settings only from the workspace root Cargo.toml; profiles in member crates are ignored. Move the [profile.release] section to the root manifest.
Exercise
What is the difference between lto = false and lto = "off"?
Show answer
false still runs "thin local" LTO across the codegen units inside each crate. "off" disables LTO completely, including between units of the same crate. "off" is slightly faster to build and can produce a slower binary.