Answer#
Cargo has two standard profiles. The debug (dev) profile builds fast and keeps debugging information; the release profile turns optimizations on. Output goes to target/debug and target/release.
One difference changes what the program does, not only how fast it is: integer overflow. In a debug build 253 + 10 on a u8 panics. In an optimized build the check is off and the number wraps around.
fn main() {
let big: u8 = 250 + std::env::args().count() as u8 * 3; // 253, not known at compile time
println!("checked_add: {:?}", big.checked_add(10));
println!("wrapping_add: {}", big.wrapping_add(10));
println!("saturating_add: {}", big.saturating_add(10));
println!("plain +: {}", big + 10);
}Without optimizations (like a debug build):
checked_add: None
wrapping_add: 7
saturating_add: 255
thread 'main' (35076) panicked at src/main.rs:6:36:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceWith -O (like a release build):
checked_add: None
wrapping_add: 7
saturating_add: 255
plain +: 7The three named methods give the same answer in both modes, which is the point of using them: checked_add returns None on overflow, wrapping_add wraps on purpose, and saturating_add stops at the maximum.
How to do it#
- Develop with
cargo run; measure speed and ship withcargo run --releaseorcargo build --release. - Never judge speed from a debug build. It is usually far slower than release.
- Where overflow is a real possibility (sizes read from a file, user input), choose the method that states what should happen.
- To keep the overflow check in release builds, add
overflow-checks = trueunder[profile.release]inCargo.toml.
Common mistakes#
- Testing only in debug mode and shipping release. A bug that wraps silently only shows in the shipped build.
- Putting a
println!in the benchmark loop and measuring the printing.
In Ruststudio#
Run > Run Release and Run > Build Release use the release profile, and Run > Switch Debug/Release Configuration changes which configuration is active.