Optimize Release Builds for Size and Speed
Intermediate10 min
Tune Cargo release profiles to produce smaller, faster binaries using LTO, codegen units, and stripping.
Prerequisites
- -Rust toolchain installed
- -A Cargo project
Steps
1
Configure release profile in Cargo.toml
Add optimization settings to the release profile for smaller and faster builds.
$ cat >> Cargo.toml << 'EOF'
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"
strip = true
EOF
codegen-units = 1 produces better optimized code but increases compile time.
2
Build the optimized release binary
Compile with the release profile to apply all optimizations.
$ cargo build --release
3
Compare debug vs release binary size
Check the size difference between debug and release builds.
$ cargo build 2>/dev/null && cargo build --release 2>/dev/null && ls -lh target/debug/myapp target/release/myapp
4
Optimize for size instead of speed
Use opt-level 's' or 'z' when binary size matters more than raw speed.
$ cat > Cargo.toml.size-opt << 'EOF'
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true
EOF
echo 'Append the above to Cargo.toml for size-optimized builds'
opt-level 'z' optimizes aggressively for size. 's' is a balance between size and speed.
5
Analyze binary size with cargo-bloat
Find which functions and crates contribute most to the binary size.
$ cargo install cargo-bloat && cargo bloat --release -n 20
Full Script
FAQ
Discussion
Loading comments...