Rust Lesson 58 – Performance | Dataplexa

Performance Optimization in Rust

In this lesson, you will learn how to make your Rust programs run faster and use less memory, and how to measure performance so that you only optimize what actually matters.

Rust is already fast because it compiles to native code with no garbage collector, but the way you write your code still decides how fast it runs.


What Is Performance Optimization?

Performance optimization means making a program run faster or use less memory without changing what it does.

In Rust, optimization usually means fewer allocations, less copying, and work that the compiler can turn into efficient machine code.


Why Performance Matters

Performance matters because:

  • Fast programs respond quickly to users
  • Efficient programs use less memory and CPU
  • Optimized code scales better under heavy load
  • Slow code wastes the speed Rust already gives you

Rust gives you control over memory and layout, so your choices decide how fast your program runs.


Measure First: Profile Before You Optimize

Never guess where your program is slow. Measure first, then optimize the part that actually costs the most time.

A simple way to measure a piece of code is std::time::Instant:

use std::time::Instant;
fn main() {
    let start = Instant::now();
    let total: u64 = (0..10_000_000).sum();
    println!("Total: {}", total);
    println!("Elapsed: {:?}", start.elapsed());
}

Run the program and look at the elapsed time before you change anything. If the number is small, the code is not your bottleneck.


Release Profile Tuning

Rust compiles debug builds for fast compilation, not fast code. Release builds optimize much more aggressively.

Add the following profile settings to your Cargo.toml file:

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
panic = "abort"

Each setting has a purpose:

  • opt-level = 3 – the highest level of optimization
  • lto = true – link-time optimization across crates
  • codegen-units = 1 – one codegen unit, so the optimizer sees more code at once
  • panic = "abort" – a smaller binary, but panics terminate instead of unwinding

These settings make compilation slower, so measure the result before you keep them.


Avoid Unnecessary Clones and Allocations

Every call to clone() copies data, and every allocation asks the system for new memory. Both take time, so avoid them when a reference will do.

Pass references instead of owned values when a function only reads its input:

fn print_length(text: &str) {
    println!("Length: {}", text.len());
}
fn main() {
    let name = String::from("Rust");
    print_length(&name);
    print_length(&name);
}

This version borrows the string each time instead of cloning it. Reserve clone() for the moments when you really need a second owned copy.


String, &str, and Cow

A String owns its text and can be changed, while a &str only borrows text owned by someone else. Borrowing avoids an allocation, so prefer &str when you do not need ownership.

When a function sometimes needs to own the text and sometimes does not, use Cow (clone on write). It borrows when it can and clones only when it must:

use std::borrow::Cow;
fn with_prefix(name: &str) -> Cow<'_, str> {
    if name.starts_with("Mr. ") {
        Cow::Borrowed(name)
    } else {
        Cow::Owned(format!("Mr. {}", name))
    }
}
fn main() {
    let a = with_prefix("Mr. Smith");
    let b = with_prefix("Smith");
    println!("{} and {}", a, b);
}

The first call borrows the string as it is, while the second call builds a new string only because the prefix is missing.


Capacity Hints with Vec::with_capacity

When a Vec grows, it allocates a new, larger block of memory and copies every element into it. If you know how many items you need, tell the Vec in advance:

fn main() {
    let mut numbers = Vec::with_capacity(1000);
    for n in 0..1000 {
        numbers.push(n);
    }
    println!("Capacity: {}", numbers.capacity());
}

This version allocates once instead of growing step by step. The same idea applies to String::with_capacity and HashMap::with_capacity.


Iterators and Zero-Cost Abstractions

An iterator in Rust is a zero-cost abstraction: code written with iterators compiles down to the same fast loop you would write by hand.

Prefer iterator methods such as map, filter, and sum over hand-written loops when they express the idea more clearly:

fn main() {
    let numbers = vec![1, 2, 3, 4, 5];
    let total: i32 = numbers.iter().map(|n| n * 2).sum();
    println!("Total: {}", total);
}

Remember that collecting results into a new Vec allocates memory, so only use collect() when you actually need a collection.


Inlining and Monomorphization

Rust compiles each generic function separately for every concrete type it is used with. This is called monomorphization, and it removes the cost of choosing a type at runtime.

The compiler can also inline small functions, replacing the call with the function's body so the call itself costs nothing. You can suggest this with #[inline]:

#[inline]
fn double(value: i32) -> i32 {
    value * 2
}
fn main() {
    println!("{}", double(21));
}

These optimizations happen automatically most of the time, so use #[inline] sparingly — the compiler usually makes the better choice on its own.


Cache-Friendly Data Layout

Computers read memory in small blocks, so data that is used together should be stored together. A program that walks through memory in order runs faster than one that jumps around.

When a loop only needs two fields, storing those fields in their own arrays keeps the data tight and cache-friendly:

fn main() {
    let xs = vec![1.0f32, 2.0, 3.0];
    let ys = vec![4.0f32, 5.0, 6.0];
    let mut sum = 0.0;
    for i in 0..xs.len() {
        sum += xs[i] + ys[i];
    }
    println!("Sum: {}", sum);
}

This layout, called a struct of arrays, is useful for large data sets that a hot loop visits again and again.


Benchmarking with cargo bench and Criterion

Timing with Instant is useful, but serious benchmarks need repeated measurements. Cargo's built-in bench harness and the Criterion crate do that for you.

Cargo's built-in bench harness only works on nightly Rust, which is why many projects use Criterion instead. Add it as a development dependency and write a small benchmark:

use criterion::{criterion_group, criterion_main, Criterion};
fn bench_sum(c: &mut Criterion) {
    c.bench_function("sum 1000", |b| {
        b.iter(|| (0..1000).sum::<i32>())
    });
}
criterion_group!(benches, bench_sum);
criterion_main!(benches);

Run it with cargo bench and compare the results before and after each change, so you only keep changes that really make the code faster.


Avoid Premature Optimization

Donald Knuth famously warned that premature optimization is the root of all evil. Optimize too early and you waste time on code that was never slow, while making the program harder to read.

Follow these rules instead:

  • Write correct, readable code first
  • Measure and profile before you optimize
  • Optimize only the hot paths that measurements point to
  • Re-measure after every change to prove it helped
  • Keep the code simple enough to understand

📝 Practice Exercises


Exercise 1

Time a loop that pushes 100,000 numbers into a Vec with std::time::Instant, then repeat it using Vec::with_capacity and compare the two timings.

Exercise 2

Rewrite a function that takes a String by value so it takes &str instead, and call it with both a String and a string literal.

Exercise 3

Add a [profile.release] section to a Cargo.toml file with opt-level = 3 and lto = true, then rebuild the project in release mode.


✅ Practice Answers


Answer 1

use std::time::Instant;
fn main() {
    let start = Instant::now();
    let mut v = Vec::with_capacity(100_000);
    for n in 0..100_000 {
        v.push(n);
    }
    println!("Elapsed: {:?}", start.elapsed());
}

Answer 2

fn greet(name: &str) {
    println!("Hello, {}!", name);
}
fn main() {
    let owned = String::from("Rust");
    greet(&owned);
    greet("Dataplexa");
}

Answer 3

[profile.release]
opt-level = 3
lto = true

What’s Next?

In the next lesson, you will build a Fullstack Rust Project and bring everything you have learned in this course together into one complete application.