The Secret of Zero-Cost Abstractions in Rust, Opened Up from the Assembly

"Higher abstractions are always slower" is an old assumption. Rust iterators can match a hand-written loop, and the assembly is there for you to read. Let's take it apart.

Read in Indonesian

Take an array of numbers, then write this in JavaScript:

JS
const total = angka
  .filter((x) => x % 2 === 0)
  .map((x) => x * 2)
  .reduce((a, b) => a + b, 0);

One line, easy to read, very tidy, right? 😅 But everyone knows the price: filter builds a new array, map builds another new array, then reduce runs over that result. For an array of a million numbers, that means two temporary arrays to allocate, discard, and clean up with the Garbage Collector, when the final answer is one single number.

That is why programmers chasing high performance often drop a level: writing raw for loops, using manual pointers, and accepting longer code for a millisecond or two. For decades that was the unwritten rule: the higher the abstraction level, the more expensive the runtime cost.

Rust challenges that rule with a principle inherited from the C++ world: Zero-Cost Abstractions. Bjarne Stroustrup, the creator of C++, phrased it like this:

In general, C++ implementations obey the zero-overhead principle: what you don't use, you don't pay for. And further: what you do use, you couldn't hand code any better.

It sounds like a marketing slogan. Which is why we won't just believe it. Let's take the assembly apart ourselves, using rustc 1.99 with LLVM behind it.

Key takeaways

  • Zero-cost abstraction does not mean free, it means moving the cost into compilation so the runtime stays clean.\n- Monomorphization copies a generic function for each concrete type, so the compiler can throw the abstraction layer away entirely. A function whose body is two trait calls shrinks to mov eax, 8 and ret.\n- An iterator chain in Rust measures as fast as a manual loop because there is no heap allocation, the bounds checks disappear, and the loop turns into SIMD instructions.\n- Closures compile into anonymous structs on the stack, and whether the compiler picks Fn, FnMut, or FnOnce shows how the closure uses the variables around it.\n- What you still pay is longer build time and binary size that can swell from duplicating functions for each concrete type.

So what is "zero-cost", exactly?

The word "zero" here does not mean free of all cost. The cost still exists; only the place you pay it moves, from runtime to compile-time. The cost moves, it does not disappear.

rustc and LLVM work extra hard during the build. They copy generic functions for each concrete type, unwrap layered abstractions into flat code, then throw away all the bookkeeping that was only overhead. What is left in the binary is ordinary machine instructions, often exactly the same as the hand-written version.

Three main mechanisms do that work: monomorphization, iterators, and closures.

Secret 1: monomorphization, polymorphism without a runtime jump

In languages using dynamic dispatch like Java or Python, calling a method from an interface means the CPU has to look up the function address at runtime, usually through a vtable. The cost of one jump is small, but the effect is large: the compiler can only see from outside the called function, so it loses the chance to throw away dead code or merge computations.

Rust can choose another path. Try this code:

RUST
trait Hitung {
    fn nilai(&self) -> i32;
}

struct A;
impl Hitung for A {
    fn nilai(&self) -> i32 { 3 }
}

struct B;
impl Hitung for B {
    fn nilai(&self) -> i32 { 5 }
}

fn pakai<T: Hitung>(x: T) -> i32 {
    x.nilai()
}

pub fn statis() -> i32 {
    pakai(A) + pakai(B)
}

pub fn dinamis(d: &dyn Hitung) -> i32 {
    d.nilai()
}

The last two functions both return 8, but the paths are far apart. Here is what rustc -O produces for statis():

ASM
statis:
    mov     eax, 8
    ret

Two instructions 🤯 No function call, no method table, no trace of A or B. The compiler did all the arithmetic at compile-time and left only the answer.

Now the &dyn version, the only way Rust forces dynamic dispatch:

ASM
dinamis:
    jmp     qword ptr [rsi + 24]

One instruction, but it jumps to an address only known while the program runs, read from the vtable at offset 24. The compiler stops there: it does not know which function will be called, so nothing can be inlined.

This copying process is what people call monomorphization. When you write pakai::<A>() and pakai::<B>(), Rust really does create two different functions in the binary, one for A and one for B. You can still force dynamic dispatch whenever you want, and sometimes that is the right call. The difference is that in Rust it is a choice, not the only road.

Secret 2: iterators as fast as a manual loop

Back to the problem from the opening: a .filter().map().sum() chain in Rust.

RUST
let numbers: Vec<i32> = (1..=10).collect();

let functional: i32 = numbers
    .iter()
    .filter(|&&x| x % 2 == 0)
    .map(|&x| x * 2)
    .sum();

let mut manual = 0;
for &x in &numbers {
    if x % 2 == 0 {
        manual += x * 2;
    }
}

println!("iterator = {functional}, for loop = {manual}");

Run it and the result is iterator = 60, for loop = 60, exactly as expected.

The interesting part is not the result but what happens after compilation. Both functions were compiled separately with rustc -O -C panic=abort, then the instructions were counted one by one:

  • The iterator version: 53 instructions, zero call instructions.
  • The manual loop version: 57 instructions, zero call instructions.

The iterator version actually has four instructions fewer, not more. Both also contain the same vector instructions: movdqu, pand, paddd, and pcmpeqd. That means the loop was turned into 128-bit SIMD that processes four i32 numbers at once. Add -C target-feature=+avx2 and both move up to ymm instructions with counts of 103 against 107, following the same pattern.

How can the compiler get that far? Three things:

  1. No heap allocation. A Rust iterator is a small struct on the stack that only stores the walk position. No new object gets created in the middle of the chain.
  2. The bounds checks disappear too. When you write array[i], the compiler has to insert an i < len check at runtime so out-of-bounds access can be caught. Through an iterator, the length and the walk direction can be proven at compile-time, so that per-element check is no longer needed. In the assembly above, only ordinary pointer arithmetic remains.
  3. The result becomes vectorization friendly. An iterator chain is a clean state machine without side effects, so LLVM easily recognizes the map-filter-reduce pattern and swaps in SIMD instructions.

This is not just theory on paper. The official book The Rust Programming Language once measured two versions of a word search over the Sherlock Holmes text: the loop version at 19,620,300 ns per iteration, the iterator version at 19,234,900 ns. The iterator version was slightly faster. Those numbers come from the book author's machine in the first edition, so treat them as a direction, not an absolute benchmark.

Secret 3: a closure is just an anonymous struct

In Garbage Collector languages, a closure that captures outside variables usually needs a heap allocation: the captured values get boxed into an object so they outlive the originating function.

In Rust it works differently. A closure is translated into an anonymous struct holding the captured variables, stored on the stack like any other value.

RUST
let batas = 5;
let dibaca = |x: i32| x > batas;                 // read only     -> Fn
let mut hitungan = 0;
let mut menambah = |x: i32| { hitungan += x; };  // changes       -> FnMut
let pemilik = String::from("halo");
let memindah = move || pemilik.len();            // moves         -> FnOnce

The difference is only in what the closure does to the variables around it. The compiler picks the trait:

  • If the closure only reads, it borrows an ordinary reference and implements the Fn trait.
  • If it changes the value, the borrow becomes &mut and the trait is FnMut.
  • If it takes ownership, the value moves into the struct, and the trait is FnOnce.

No allocator is involved, because everything lives on the stack. Run it and the output is: dibaca(7) returns true, hitungan ends at 7, and the length of pemilik stays 4 even though its contents already moved into the closure.

The tax you still have to pay

If the abstraction really has zero cost, why isn't every language like this? Because the cost does not vanish, it just moves.

Longer build time. Borrow checker analysis, monomorphization, and aggressive optimization are heavy work. But be careful with the popular explanation that blames monomorphization alone: one Rust compiler developer has said that experiments in Rust's early days showed monomorphization was not the main cause, because even dynamic versions need a lot of bookkeeping code that has to be optimized. The real causes are spread out, from large dependency trees to the LLVM optimization stage itself.

Binary size can swell. Each concrete type produces its own copy of the function. Use Vec<i32>, Vec<u64>, and Vec<String> in one program and you get three copies of similar code. In a small program the effect is thin; in a large project, code bloat is real. One cure: use &dyn Trait for code that is called rarely and does not need to be fast. As we saw above, that really does save code.

So the price of zero-cost abstraction is not zero. What changes is who pays it: your build machine and the person reading the code later, not the user's CPU.

Closing

What makes this principle interesting is not just the performance, but the permission it grants: you don't have to feel guilty about writing chained iterators, composing modular traits, or creating closures in performance-critical code. If there really is a cost, that cost is placed somewhere much cheaper for you to pay.

If you want to see the assembly yourself, paste the code above into Compiler Explorer, pick a stable rustc version, then add -O -C panic=abort in the arguments column. The fastest way to stop believing and start checking. Happy systems programming! 🦀

Get better at shipping code.

Join the other developers getting tech updates, tips, and relaxed tutorials in their inbox every week.

Stay in the loop

Tech updates, coding tips, and relaxed insights straight to your inbox every week.

No spam. Unsubscribe anytime.

Read next

See all
Struktur DataWhat a Linked List Actually Is

A linked list is a linear chain of nodes, each holding data and a pointer to the next node. Here is what that chain looks like, what it costs next to an array, and the same minimal implementation in Java, Python, and JavaScript.

For developers who learn by struggling

© 2026 Inva.dev.