Sub topic 10
Debug builds versus release builds
This chapter assumes you have Rust installed through rustup and can create a project with cargo new. You should also know how to run cargo build and cargo run. Here you will learn what separates the two default build modes, where each puts its output, how to measure the difference, and how to adjust the settings.
Two profiles, one source tree
Cargo compiles your code under a profile. A profile is a named set of compiler settings. Cargo ships with built-in profiles, and two matter for everyday work:
- The
devprofile is whatcargo buildandcargo runuse by default. People call the result a debug build. - The
releaseprofile is selected with the--releaseflag. It produces a release build.
The source code is identical in both. Only the compiler settings change. The dev profile favors fast compile times and easy debugging. The release profile favors fast programs and small output, and it pays for that with longer compile times.
cargo build
cargo build --releaseThe first command writes to target/debug. The second writes to target/release. Both directories can exist side by side, so building one does not erase the other.
Where the output goes
Cargo puts all build output in the target directory at the project root. For a project named hello_cargo, on Linux or macOS, the layout looks like this:
hello_cargo/
├── Cargo.toml
├── Cargo.lock
├── src/
│ └── main.rs
└── target/
├── debug/
│ └── hello_cargo
└── release/
└── hello_cargoOn Windows the executables end in .exe. You can run either binary directly:
./target/debug/hello_cargo
./target/release/hello_cargocargo run builds if needed and then runs the binary. Add --release to run the optimized one:
cargo run
cargo run --releaseThe target directory holds generated files, so it should not go into version control. The .gitignore file that cargo new creates already lists it.
What differs between the profiles
The default settings of the two profiles differ in a few ways that you will notice.
| Setting | `dev` default | `release` default | Effect |
|---|---|---|---|
| `opt-level` | `0` | `3` | How hard the compiler optimizes. `0` means almost none. |
| `debug` | `true` | `false` | Whether debug information is included for debuggers. |
| `debug-assertions` | `true` | `false` | Whether `debug_assert!` checks run. |
| `overflow-checks` | `true` | `false` | Whether integer overflow panics. |
| `incremental` | `true` | `false` | Whether Cargo reuses earlier compile work. |
Check the Cargo reference for your installed version if you need the exact current defaults. The values above are the long-standing ones.
Optimization level
opt-level ranges from 0 to 3, plus "s" and "z", which optimize for size. At 0 the compiler translates your code almost literally. At 3 it inlines functions, unrolls loops, and removes dead code. Optimized programs can run many times faster than unoptimized ones. Iterator-heavy and numeric code often shows the largest gap.
Integer overflow
This difference catches people off guard. In a debug build, arithmetic that overflows an integer panics. In a release build, the default is to wrap around silently using two's complement.
fn main() {
let mut value: u8 = 250;
for _ in 0..10 {
value += 1;
println!("{value}");
}
}With cargo run, the program prints 251 through 255 and then panics with "attempt to add with overflow". With cargo run --release, it prints 251 to 255, then 0, 1, 2, 3, 4. Same source, different behavior.
If you want explicit overflow behavior in every build, use the integer methods checked_add, wrapping_add, saturating_add, or overflowing_add. They behave the same under both profiles.
fn main() {
let value: u8 = 250;
println!("{:?}", value.checked_add(10));
println!("{}", value.wrapping_add(10));
println!("{}", value.saturating_add(10));
}This prints None, 4, and 255.
Debug assertions
The debug_assert!, debug_assert_eq!, and debug_assert_ne! macros run only when debug-assertions is on. Use them for expensive sanity checks that you do not want to pay for in production. Plain assert! always runs. Do not put checks you rely on for correctness or safety inside debug_assert!.
Measuring the difference
Run a simple CPU-bound program in both modes to see the gap. Put this in src/main.rs:
use std::time::Instant;
fn main() {
let start = Instant::now();
let mut sum: u64 = 0;
for i in 0..500_000_000u64 {
sum = sum.wrapping_add(i * i % 7);
}
println!("sum = {sum}");
println!("elapsed = {:?}", start.elapsed());
}Then run:
cargo run
cargo run --releaseThe release build is typically many times faster. The exact ratio depends on your hardware, so treat any number you see as a local measurement. Do not benchmark with cargo run alone. A debug build can mislead you badly about how fast your program really is.
Note that the release compiler may also transform a loop like this heavily, since it can see that only the final sum is used. For serious benchmarking, use a dedicated tool such as the criterion crate and pass inputs through std::hint::black_box so the optimizer cannot remove the work.
Compile time and binary size
Optimization costs time. A release build usually takes noticeably longer than a debug build of the same project, and the gap grows with project size. Dependencies are compiled with the same profile as your code, so the first cargo build --release of a project with many crates can take a while. Later builds only recompile what changed.
Release binaries are usually faster but not necessarily smaller. Debug builds carry debug information, which makes them larger. You can see this with a quick size comparison:
ls -lh target/debug/hello_cargo target/release/hello_cargoOn Windows, use dir target\debug\hello_cargo.exe target\release\hello_cargo.exe instead.
Choosing the right command
Day to day, you do not always need a full build. Three commands cover most situations:
| Command | Produces a binary? | Use it when |
|---|---|---|
| `cargo check` | No | You only want to know whether the code compiles. It is the fastest feedback loop. |
| `cargo build` / `cargo run` | Yes, in `target/debug` | You are developing and debugging. |
| `cargo build --release` / `cargo run --release` | Yes, in `target/release` | You are measuring performance or shipping. |
Customizing profiles in Cargo.toml
You can override any profile setting in Cargo.toml by adding a [profile.<name>] table. Settings you do not list keep their defaults.
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
[profile.dev]
opt-level = 1
[profile.release]
lto = true
codegen-units = 1
panic = "abort"
strip = trueHere is what the common options do:
opt-level = 1indevgives a little optimization while keeping fast builds. It helps when a debug build is too slow to use but you still want debug information.lto = trueturns on link-time optimization. The compiler can then optimize across crate boundaries. It lengthens the build and often improves speed and size.codegen-units = 1makes the compiler process the crate as one unit. This can enable better optimization at the cost of build time, since it reduces parallelism.panic = "abort"ends the program immediately on a panic, with no stack unwinding. This shrinks the binary, but destructors will not run on panic, and tests and some libraries expect unwinding.strip = trueremoves symbols from the binary, which reduces size.
Profile settings go in the manifest of the workspace root. Cargo ignores [profile] tables in the manifests of other workspace members and in dependencies, and it prints a warning.
A useful middle ground
Sometimes you want release-level speed with debug symbols, for example to run a profiler. Set debug in the release profile:
[profile.release]
debug = trueThis keeps the optimizations but adds symbol information so profilers can show function names and line numbers.
Custom profiles
You can also define your own profile that inherits from another one:
[profile.release-with-debug]
inherits = "release"
debug = trueBuild with it using --profile:
cargo build --profile release-with-debugThe output goes to target/release-with-debug. The dev profile's output directory is the one exception to the naming rule, because it maps to target/debug.
Common mistakes
- Shipping a debug binary. If you copy
target/debug/...to a server, you ship slow code with debug information. Build with--releaseand copy fromtarget/release. - Looking in the wrong directory. After
cargo build --release, the binary is not intarget/debug. Check the right folder. - Relying on overflow panics in production. They are on by default in debug builds only. Use checked arithmetic where overflow matters.
- Putting needed side effects in
debug_assert!. The expression is not evaluated in release builds, so the side effect disappears. - Setting
panic = "abort"and expectingcargo testto work as usual. The test harness relies on unwinding to catch failing tests. Cargo ignores thepanicsetting for thetestprofile, but libraries and mixed setups can still behave differently, so verify after changing it. - Editing profile settings in a workspace member. Only the workspace root's settings apply.
Summary of the model
Cargo builds under a profile. dev is the default and optimizes for compile speed and debuggability. release optimizes for runtime speed. Output lands in target/debug or target/release. Behavior can differ between them, most notably integer overflow and debug_assert!. You tune either profile through [profile.*] tables in the workspace root Cargo.toml.
Exercise
You run cargo build --release on a project named shop, and then run ./target/debug/shop. The program runs slowly and you suspect the release flag did nothing. What is wrong, and how do you run the optimized binary?
Show answer
The release build writes its binary to target/release/shop, not target/debug/shop. The file in target/debug is either missing or an older unoptimized build. Run ./target/release/shop, or use cargo run --release, which builds if needed and runs the optimized binary.
Exercise
A function computes let total: u32 = a + b; where a and b are large. It panics during development with cargo run, but returns a wrapped value in production, which was built with --release. Why does this happen, and how can you make the behavior identical in both builds?
Show answer
Overflow checks are on in the dev profile and off in the release profile, so the same addition panics in one and wraps in the other. To get the same behavior everywhere, use explicit methods such as a.checked_add(b) (returns None on overflow), a.wrapping_add(b), or a.saturating_add(b). Alternatively, set overflow-checks = true under [profile.release] in Cargo.toml.
Exercise
You want a profile named profiling that has release optimizations plus debug symbols, so a profiler can show function names. Write the Cargo.toml section and the command that builds with it. Where does the binary end up?
Show answer
Add this to the workspace root Cargo.toml:
[profile.profiling]
inherits = "release"
debug = true
Build with cargo build --profile profiling. The binary is written under target/profiling/.