Systems Rust · 19 min · free lesson

Performance

Rust is fast by default; the wins left are allocation and algorithm.

Core idea

Measure representative workloads with the target optimization profile; debug timings do not predict release performance.

Diagram for Performance: a Rust code example flows to the lesson rule and the key observation.
One allocation up front instead of a handful of geometric regrowths.

Understand it

Iterator chains can optimize similarly to hand-written loops, but inspect representative hot paths rather than assuming identical machine code. What does cost is allocating in a hot loop, cloning to satisfy the borrow checker, and choosing the wrong container. Reserve capacity when the size is known, borrow instead of cloning, and measure with the profile and target you intend to ship. Debug timings describe that debug build; they are not a reliable prediction of optimized performance.

Performance work begins with a workload and a measurement. A release build is essential because debug checks and missing optimizations can dominate a microbenchmark. Use realistic input sizes and record latency distributions or throughput, not one attractive timing. Profile before changing code: time may be in parsing, allocation, I/O, locking, or an algorithmic choice far from the line that looks complicated. An iterator chain is often optimized well, but verify hot paths rather than treating any syntax as inherently free or expensive.

In the example, Vec::with_capacity(1_000) avoids repeated growth when the final size is known. It does not avoid initializing each pushed element. Borrowing a slice in total avoids cloning the vector just to read it. Next, compare a linear search with a HashMap lookup for your actual access pattern; the map's build cost and memory overhead can outweigh faster repeated lookups for a tiny input. Change one variable at a time, rerun under similar conditions, and keep a correctness test alongside the benchmark. State the tradeoff: perhaps more memory buys lower tail latency, or an extra allocation simplifies a cold path. Optimize the measured bottleneck and stop when the improvement is no longer meaningful to the product.

Beware of a fast path that worsens the slowest cases. Reserving capacity may reduce allocations but increase peak memory if most inputs are tiny. A hash map may speed lookup while making iteration order unsuitable for a UI. State the workload distribution and the user-visible metric before choosing the optimization. Keep the simpler version if the measured gain is negligible.

Read the code

let mut values = Vec::with_capacity(1_000);
for index in 0..1_000 {
    values.push(index * 2);
}

// Borrow instead of cloning to read.
fn total(values: &[usize]) -> usize {
    values.iter().sum()
}

One allocation up front instead of a handful of geometric regrowths.

Practice starter

fn shout(items: &Vec<String>) -> Vec<String> {
    items.clone().iter()
        .map(|s| s.to_uppercase())
        .collect()
}

Practise this code in Playground ↗

Try it

Find one clone or one allocation in a loop and remove it.

What success looks like: Behaviour is unchanged and the allocation count drops.

Check your understanding

Which change removes the wasted work?

Reveal the answer
  1. Take &[String] and drop the clone
  2. Return a reference to the first name
  3. Use a HashMap

The clone is never needed: map already produces new Strings.

Go deeper

Common misconception: “items.clone() is needed before reading the strings in a shared Vec.”

Reading through &[String] needs no clone, because map builds new Strings anyway. Measure a release build to see what the removed work actually cost.

  1. Reserve first: Vec::with_capacity(1_000) allocates room for 1,000 elements before the loop, while values is still empty.
  2. Push without growing: All 1,000 pushes fit in that capacity, so none reallocates. Without the reservation, the buffer would regrow geometrically several times.
  3. Borrow to read: total takes &[usize], so it sums the values with no copy and the caller keeps values.

Transfer challenge: Print values.capacity() after each push, with and without with_capacity, and count the changes. Then time both in a release build and say whether the difference matters here.

Connections

  • FFI: extern "C", repr(C), and raw pointers
  • Rust Idioms: Newtype, builder, and typestate
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Performance (courseId "systems", lessonId "performance")
Link: https://crabrix.com/learn/systems/performance/
Goal: Measure representative workloads with the target optimization profile; debug timings do not predict release performance.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/performance) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.