FAQ - Help and questions

What is the difference between a debug build and a release build in Rust?

#cargo#release#overflowpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

cargo build makes a debug build: quick to compile, slow to run, with overflow checks that panic. cargo build --release makes an optimized build that runs much faster but compiles slower, and integer overflow wraps silently. Test with both, and use checked_ or wrapping_ methods when overflow is possible.

Checked with rustc 1.93.0, Windows 11 (the same file compiled without and with -O)

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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):

text
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 backtrace

With -O (like a release build):

text
checked_add:    None
wrapping_add:   7
saturating_add: 255
plain +:        7

The 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 with cargo run --release or cargo 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 = true under [profile.release] in Cargo.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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet