Recipe
Shrink a release binary
Use when: a release executable is bigger than you want to download or ship, and you're choosing profile settings
Goal: a [profile.release] where every setting was measured and kept only because it paid for its cost
Taught in Release builds and binary size
Quick recipe
-
1
Build with
cargo build --releaseand no size settings, and write down the size of the file intarget/release/.Why: every later number means something only next to the one you started from.
-
2
Add a single setting (
strip = truefirst), runcargo cleanandcargo build --release, and record the size and the build time.Example
On
dockstat,strip = truetook 925,536 bytes to 730,592 with no change in build time.Why: settings interact, and a partial rebuild can hide or blame the wrong change.
-
3
Add
lto = trueandcodegen-units = 1, then tryopt-level = "s"or"z"on top.Why: these let the optimizer see the whole program, and the size-first opt-levels often only pay off once it can.
-
4
Keep it only if nothing in the program depends on unwinding: no thread that is allowed to panic while others carry on, no
catch_unwind, no cleanup inDropthat must happen on a panic.Why: it's the one size setting that changes what the program does, not only how big it is.
-
5
Time the release program on real input with and without the final settings.
Why: a smaller file that runs slower may not be the trade you wanted.