FAQ - Help and questions

Why is my ported Rust program slower than the original, and what do I check first?

#porting#performance#cargopublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Check three things in order. Build with cargo build --release, because a debug build can be many times slower. Then look for clone calls and collect calls that copy data your old language only passed by reference. Last, look for work inside loops such as printing, formatting and locking.

Checked with rustc 1.93.0, Windows 11

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

#1

Answer#

A port that runs slower than the program it replaced almost always has one of a few causes, and the first is the cheapest to check: the build profile. cargo build and cargo run make a debug build, which turns off most optimisation so that compiling is quick and debugging is easy. cargo build --release makes the build you should measure.

The second cause comes from habits of the old language. In Java, C#, Python and JavaScript, passing a list to a function passes a reference, which costs nothing. In Rust, passing a Vec<T> by value moves it, and the quick fix for a compiler error (.clone()) copies every element. The program below does the same count two ways, 200 times over a list of 20,000 strings, and prints the time for each in the build it was compiled with:

src/bin/slow.rsrust
use std::time::Instant;

fn make_words(n: usize) -> Vec<String> {
    (0..n).map(|i| format!("Word{}", i % 1000)).collect()
}

// Copies the whole list on every call (a habit carried over from languages where passing a list is cheap).
fn count_cloning(words: &Vec<String>, needle: &str) -> usize {
    let copy = words.clone();
    copy.iter().filter(|w| w.as_str() == needle).count()
}

// Borrows the list.
fn count_borrowing(words: &[String], needle: &str) -> usize {
    words.iter().filter(|w| w.as_str() == needle).count()
}

fn main() {
    let words = make_words(20_000);
    let mut a = 0;
    let t = Instant::now();
    for _ in 0..200 {
        a += count_cloning(&words, "Word7");
    }
    let t_clone = t.elapsed();
    let mut b = 0;
    let t = Instant::now();
    for _ in 0..200 {
        b += count_borrowing(&words, "Word7");
    }
    let t_borrow = t.elapsed();
    let profile = if cfg!(debug_assertions) { "debug" } else { "release" };
    println!("{profile}: cloning {} ms, borrowing {} ms (results {a} {b})", t_clone.as_millis(), t_borrow.as_millis());
}

Three runs of each build on one Windows 11 laptop (rustc 1.93.0, other programs running at the same time, so expect noise):

text
debug: cloning 594 ms, borrowing 137 ms (results 4000 4000)
release: cloning 291 ms, borrowing 2 ms (results 4000 4000)
debug: cloning 568 ms, borrowing 153 ms (results 4000 4000)
release: cloning 297 ms, borrowing 2 ms (results 4000 4000)
debug: cloning 710 ms, borrowing 178 ms (results 4000 4000)
release: cloning 334 ms, borrowing 4 ms (results 4000 4000)

Two things stand out. The release build is faster than the debug build in both columns. And in the release build the copying version stays far behind the borrowing one, because allocating and copying 20,000 strings 200 times is real work that no optimiser removes. The borrowing loop is so cheap here that it is close to the limit of what this small test can measure, so do not read the "2 ms" as a general figure.

How to do it#

  1. Measure a release build: cargo build --release, then run target/release/<name>.
  2. Search the hot path for .clone(), .to_string(), .to_vec() and .collect::<Vec<_>>(). Ask for each one whether the value needs to be owned, or whether a &T, &str or &[T] would do. Change function parameters first: &[T] instead of &Vec<T>, &str instead of &String.
  3. Look at what runs per iteration: println! (locks and flushes standard output), format! (allocates), lock() on a mutex, and HashMap lookups that could be hoisted out of the loop.
  4. Only then use a profiler. A profile tells you which function is hot; the steps above remove the common causes without one.

Common mistakes#

  • Timing cargo run without --release and concluding that Rust is slow.
  • Cloning to get past a borrow-checker error and leaving the clone in a hot loop (the thread on the borrow checker shows when a clone is the right fix).
  • Comparing a program that does the work with one that does not. Check that both versions produce the same output first (the thread on golden files shows how).

Can I make release builds faster still?#

Yes, with settings in [profile.release] of Cargo.toml such as lto and codegen-units = 1, at the cost of longer compile times. Measure before and after, because the gain depends on the program.

Is the debug build ever the right one to measure?#

No. Use it to find bugs, not to judge speed.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet