Chapter 14 of 16 · Part IV, Under the hood
Zero-cost abstractions, and where the cost actually lands
What zero-cost really claims, how a Rust iterator pipeline compiles to a loop, what the LINQ version allocates, bounds checks, where the claim fails.
Read this after generics and iterators. Your goal is to turn a performance claim into a measurement: compare the same calculation, identify allocations, and keep the optimizer from deleting the work. The byte counts belong to the stated experiment, not every runtime version.
The phrase gets repeated so often that it stops meaning anything, so here is the actual claim: you cannot hand-write it better, and you do not pay for what you do not use. Not "free". Not "faster than C#".
Rust borrowed the wording from C++. The Rust Book quotes Bjarne Stroustrup's zero-overhead principle directly, and the useful half is the first sentence: "What you don't use, you don't pay for." The second half is the ambitious one, that what you do use, you could not hand code any better.
Both halves are testable.
Two pipelines, and what exists at run time
A complete Rust program. Paste it into src/main.rs and run it.
#[derive(Clone, Copy, PartialEq)]
enum Status {
Ok,
Failed,
}
struct Reading {
status: Status,
bytes: u64,
}
fn total_ok_bytes(readings: &[Reading]) -> u64 {
readings
.iter()
.filter(|r| r.status == Status::Ok)
.map(|r| r.bytes)
.sum()
}
fn main() {
let mut readings = Vec::new();
for i in 0..1000u64 {
readings.push(Reading {
status: if i % 3 == 0 { Status::Failed } else { Status::Ok },
bytes: i,
});
}
let chain = readings
.iter()
.filter(|r| r.status == Status::Ok)
.map(|r| r.bytes);
println!("pipeline size: {} bytes", std::mem::size_of_val(&chain));
println!("total: {}", total_ok_bytes(&readings));
}
On a 64-bit target it prints pipeline size: 16 bytes, then the total.
Sixteen. That is the size of a bare slice iterator and nothing more, because slice::Iter is two pointer-sized fields for a non-zero-sized element type, and the two adapters wrapped around it add zero. The optimizer may keep it in registers or eliminate its representation; source-level size does not dictate register allocation.
The C# that does the same work, also complete, also runnable.
using System;
using System.Linq;
enum Status { Ok, Failed }
readonly record struct Reading(Status Status, long Bytes);
static class Program
{
static long TotalOkBytes(Reading[] readings) =>
readings.Where(r => r.Status == Status.Ok).Select(r => r.Bytes).Sum();
static long TotalLoop(Reading[] readings)
{
long total = 0;
foreach (var r in readings)
if (r.Status == Status.Ok) total += r.Bytes;
return total;
}
static long Measure(Func<long> f)
{
long before = GC.GetAllocatedBytesForCurrentThread();
f();
return GC.GetAllocatedBytesForCurrentThread() - before;
}
static void Main()
{
var readings = new Reading[1000];
for (int i = 0; i < readings.Length; i++)
readings[i] = new Reading(i % 3 == 0 ? Status.Failed : Status.Ok, i);
for (int i = 0; i < 20; i++) { TotalOkBytes(readings); TotalLoop(readings); }
Console.WriteLine("chain type: " +
readings.Where(r => r.Status == Status.Ok).Select(r => r.Bytes).GetType().Name);
Console.WriteLine("linq bytes: " + Measure(() => TotalOkBytes(readings)));
Console.WriteLine("loop bytes: " + Measure(() => TotalLoop(readings)));
}
}
This is illustrative output from .NET 9 x64 Release. Runtime upgrades and JIT optimizations can change it:
chain type: ArrayWhereSelectIterator`2
linq bytes: 112
loop bytes: 0
GC.GetAllocatedBytesForCurrentThread is exact rather than sampled, so this is a per-call byte count and not a benchmark estimate. The hand-written loop allocates nothing. The LINQ version allocates on every call, and the 112 falls out of the library source, which is worth walking through because it is not what most people guess.
The 112 bytes, itemized
Start with the good news, because LINQ is far less naive than the folklore says.
The chain type is ArrayWhereSelectIterator, which means the two stages collapsed into one object. That is not the JIT being clever. It is written into the library: Where.cs defines ArrayWhereIterator, ListWhereIterator and IEnumerableWhereIterator, and each of them overrides Select to return a fused WhereSelect iterator instead of stacking another layer. Enumerable.Where picks the array shape or the List<T> shape when the source is one of those, so the common cases skip the interface indirection entirely.
The delegates are free too. Neither lambda captures anything, so Roslyn hoists both into a static cache and reuses them forever. The C# specification explicitly allows this: conversions of semantically identical anonymous functions with the same set of captured variables to the same delegate type are permitted, though not required, to return the same delegate instance. After the first call the cached instances are reused, which is why the program above warms up before it measures.
The 112 bytes are two objects. The field lists come from Where.cs and from Iterator.cs, whose base class contributes _threadId as an int, _state as an int, and _current typed as the element.
Where allocates an ArrayWhereIterator<Reading> first. Object header and method table pointer 16, source array reference 8, predicate delegate reference 8, thread id 4, state 4, and a Reading field for the current value at 16, since a 4 byte enum followed by an 8 byte long pads to 16. That is 56 bytes, and it becomes garbage immediately, because Select reads its fields and throws it away.
Select then allocates the ArrayWhereSelectIterator<Reading, long>. Header 16, source 8, predicate 8, selector 8, thread id 4, state 4, current long 8. Also 56.
In that implementation, 56 plus 56 is 112 bytes per call. These are layout details of one runtime on one architecture, not a contract, so treat the shape as the lesson and re-measure if the exact figure matters to you.
Enumerating does not add more. Iterator<TSource> is its own enumerator, and its GetEnumerator returns this when _state is still 0 and the calling thread is the one that created it, cloning only when you enumerate a second time. Sum then asks TryGetSpan for a contiguous view, does not get one from a where-select iterator, and falls back to a plain foreach, which allocates nothing.
Now make one lambda capture a local:
static long TotalCapturing(Reading[] readings, long threshold) =>
readings.Where(r => r.Bytes > threshold).Select(r => r.Bytes).Sum();
That comes to 200 bytes per call instead of 112. The extra 88 is a display class holding the captured long, 16 bytes of header plus an 8 byte field, which is 24, plus a delegate object at 64, which is a 16 byte header over the six reference-sized fields Delegate and MulticastDelegate declare between them. The second lambda still captures nothing, so it still comes out of the static cache.
Capturing a local commonly adds a closure object and delegate allocation. Caching and optimization affect what survives; measure your actual code.
The Rust side is a struct, and then it is a loop
Nothing above happens in the Rust version, and the reason is that Rust's iterator adapters are not objects that wrap other objects. They are structs that contain other structs, by value.
The definitions in the standard library are two fields each:
pub struct Filter<I, P> {
iter: I,
predicate: P,
}
pub struct Map<I, F> {
iter: I,
f: F,
}
So readings.iter().filter(p).map(f) has the type Map<Filter<slice::Iter<Reading>, P>, F>, where P and F are the anonymous types of your two closures. Neither closure captures anything, so both are zero-sized, and the whole nest is exactly the 16 bytes of the slice iterator. There is no object, no header, no allocation, and nothing for a collector to trace.
Then generic code gets stamped out per concrete type. Filter::next for your specific predicate type is a separate function from Filter::next for anyone else's, which means the compiler knows the exact closure body it is calling and can inline it. No virtual call, no delegate invoke, no guarded devirtualization needed because there was never a call to devirtualize.
There is a second mechanism worth knowing, because it is why iterator chains optimize so unusually well. sum is implemented in terms of fold, and adapters like Filter override fold rather than relying on repeated next calls. That converts the pipeline from external iteration, where the consumer pulls one item at a time through a chain of state machines, into internal iteration, where the source drives a single loop and the adapters are just closures called inside it. What LLVM sees at that point is one loop over a contiguous slice with two inlined bodies, which is the loop you would have written.
Closures are types, and that is the whole difference
In C# a lambda becomes a delegate. Func<Reading, bool> is one type, whatever the body is, and two different predicates are two instances of the same type. That uniformity is why you can put a lambda in a field, swap it at run time, and store a dictionary of them without thinking about it.
In Rust a closure expression produces a value with a unique, anonymous type that cannot be written out, approximately equivalent to a struct holding the captured values, with an impl of Fn, FnMut or FnOnce generated for it. Two closures with identical bodies are two different types.
The compiler will tell you this the first time you fight it:
fn main() {
let mut a = 0u8;
let foo: fn(u8) -> u8 = |v: u8| { a += v; a };
}
error[E0308]: mismatched types
--> src/main.rs:3:29
|
3 | let foo: fn(u8) -> u8 = |v: u8| { a += v; a };
| ------------ ^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found closure
| |
| expected due to this
|
= note: expected fn pointer `fn(u8) -> u8`
found closure `{closure@src/main.rs:3:29: 3:36}`
note: closures can only be coerced to `fn` types if they do not capture any variables
--> src/main.rs:3:39
|
3 | let foo: fn(u8) -> u8 = |v: u8| { a += v; a };
| ^ `a` captured here
Read that note carefully, because it is the whole model in one line. A closure with no captures is a function, and coerces to a plain function pointer. A closure with captures is a value carrying data, and there is no single type that can hold it alongside every other closure.
The payoff is the 16 byte pipeline above. The price is that impl Fn(...) in a signature means "one specific closure type chosen at compile time", so a function cannot return two different closures from two branches:
fn pick(flag: bool) -> impl Fn(u32) -> u32 {
if flag {
|x| x + 1
} else {
|x| x * 2
}
}
Trimmed to the lines that matter, the diagnostic reads:
error[E0308]: `if` and `else` have incompatible types
= note: expected closure `{closure@src/main.rs:3:9: 3:12}`
found closure `{closure@src/main.rs:5:9: 5:12}`
= note: no two closures, even if identical, have the same type
= help: consider boxing your closure and/or using it as a trait object
Take the help. Box<dyn Fn(u32) -> u32> gets you back to exactly what C# had: one allocation, one indirect call, one type that any closure fits into. That is the honest framing of the whole chapter in miniature. Rust's default is the specialized version with no runtime cost, and the general version is available for one allocation when you need it. C# delegate APIs use a uniform representation, while value-type generic designs and function pointers offer other options. The JIT can also specialize some delegate calls.
Bounds checks, honestly
This is the part of the zero-cost pitch that gets oversold, so take it slowly.
Rust bounds-checks v[i] and panics on failure. .NET bounds-checks array and span indexing and throws IndexOutOfRangeException. Both are on by default in release builds. Neither language lets you index past the end and keep going.
Both compilers remove the check when they can prove it is redundant. RyuJIT has a dedicated range analysis phase whose stated job is to eliminate array index range checks based on value numbers and assertions, and the canonical for (int i = 0; i < arr.Length; i++) shape is the one it handles best. Rust leans on LLVM, and the reliable pattern is the same idea from the other direction: iterate rather than index, so the bound is structural and there is nothing to check.
Both have known gaps, and they are the same kinds of gaps: the analysis is pattern matching on shapes it recognizes, and anything outside those shapes keeps its check. The dotnet issue tracker carries a steady stream of them, such as checks that survive when a loop touches several different indices and a redundant check that is not folded away after an earlier one already proved the range. Rust has the mirror image: an index expression carries a check unless LLVM can see the bound, so for i in 0..v.len() { v[i] } is usually fine and anything that indexes a second slice with the same variable usually is not, which is why zip and iter().enumerate() are the idiomatic shapes.
Both give you an escape hatch. Rust has get_unchecked, which is unsafe. C# has Unsafe.Add and MemoryMarshal.GetReference, which are the same thing with a different spelling.
Nobody wins this one. If you are moving to Rust expecting free indexing, you are moving for the wrong reason.
Where the claim actually fails
"You could not hand code it any better" is an aspiration, not a theorem, and it is worth naming the cases where it is false.
The clearest one is a place where C# is straightforwardly better. Enumerable.Sum over an int[] in modern .NET does not do what you think. It calls TryGetSpan, and if the source is contiguous it takes a vectorized path that accumulates four Vector<T> per iteration and tracks overflow by watching sign bits, then checks once at the end instead of branching per element. The gate is real and the source says so: it needs Vector<T>.Count above 2 and a span of at least four vectors, so on a 128 bit machine long sums stay scalar. Everything that misses the gate falls into a checked scalar loop. Either way you get a guaranteed OverflowException, and often SIMD, from a naive nums.Sum().
Rust's Iterator::sum on a primitive integer panics on overflow only when overflow checks are enabled, which by default means debug builds. In release it wraps. So the same program can be correct in debug and silently wrong in release, and the language considers that fine, because wrapping is defined behavior rather than undefined behavior. If you want the C# semantics you give up sum and write iter.try_fold(0u64, u64::checked_add), then handle the None, which is more code and is not what the ergonomic path hands you.
That is a real point against Rust, and it is worth internalizing early: Rust removed the tax on abstraction, not the tax on arithmetic you did not think about.
There are softer failures too. format! allocates. Trait objects cost an indirect call. Deeply nested iterator chains occasionally defeat LLVM's inliner, and when that happens the abstraction is not free and the only way to know is to look at the generated code. The claim holds far more often than it fails, which is why it is worth making, but it is a claim about a compiler doing its job rather than a guarantee written into the language.
Where you do pay
Compile time. This is the tax you feel every day, and monomorphization is the mechanism. A generic function is not machine code until someone picks concrete types for it, so the compiler stamps out a separate copy per instantiation. Vec<u64> and Vec<String> produce two copies of the generated code, and the work scales with the number of instantiations rather than the number of source lines.
The part that surprises people arriving from .NET is where that work happens. A generic function from a dependency is not machine code in the dependency's rlib. It is stored as MIR, and it gets collected and codegenned inside your crate, because only your crate knows which types you instantiated it with. Pull in a library that is generic over everything and you have pulled its code generation into your build. Add the trait solver and the borrow checker on top, both of which are doing real proof work, and the result is a compiler that does a lot more per build than a JIT-backed toolchain that defers specialization to run time.
This is not a small complaint from a fringe of users. In the Rust project's own 2025 compiler performance survey, around 45 percent of respondents who had stopped using Rust listed long compile times as one of the reasons. Type checking is separable from code generation, which is why cargo check is so much faster than cargo build, and that separation is the single most useful fact about the Rust build model. It is also what the survey found people already lean on hardest: about 60 percent said they run a cargo command after each change, with cargo check the most common.
Binary size. Ten reachable instantiations can increase generated code, although inlining, deduplication, and dead-code elimination affect what remains. Usually irrelevant, occasionally not, and dyn is the lever: shared caller code plus implementation-specific methods and vtables, in exchange for indirect calls. If a generic function is large and cold, taking &dyn Trait instead of impl Trait is a straight trade of a little speed for a lot of size.
Runtime costs you opted into. Rc increments a plain counter. Arc does an atomic one. RefCell reads and writes a borrow counter on every borrow and panics if the counter says no. dyn costs an indirect call. None of these are free, and none of them are imposed on code that does not use them, which is the second half of the original claim and the more important half.
Your time. The first month is slower. That is a real cost and it belongs on the list.
Where the allocations show up at three thousand requests a second
At the scale of a script none of this is visible. At the scale where it matters, the pattern is consistent and it is about variance rather than averages.
Take a service at 3,000 requests per second where each request runs ten LINQ queries shaped like the one above. At 200 bytes a query that is 6 MB per second of short-lived garbage, which is not a large number, and that is the point worth being honest about. Gen 0 handles it easily, which is exactly the workload it was designed for, and the cost does not appear as latency on the request that allocated it. It appears as collection frequency, and eventually as the occasional promotion into gen 1 and gen 2, and it lands on some unrelated request's tail latency. Server GC and background collection push the pauses down a long way, but they do not make the work disappear, and the query allocation is only one contributor sitting on top of everything else the request allocates.
The Rust version of that pipeline allocates nothing, so there is no collector to schedule and no pause to land anywhere. That is the actual argument for Rust in a hot path, and notice how narrow it is. It is not "Rust is faster". Average throughput on a well-tuned .NET service is frequently competitive and sometimes better, because the JIT knows things an ahead-of-time compiler cannot. The argument is that the p99.9 stops having a component you did not put there.
The second thing that shows up at scale is resident memory. A .NET process holds a heap sized by the collector's policy rather than by your live set, and the gap between the two is often large. If you are running one agent per host across ten thousand hosts, or packing containers by memory limit, that gap is money. Rust still pays for allocator metadata, fragmentation, reserved capacity, stacks, code, and pages retained after a free. Resident memory is not simply the live payload size in either language.
How to accidentally measure nothing
Measuring a debug build. Rust's debug profile compiles at opt-level = 0 with integer overflow checks on, so the iterator fusion this whole section is about does not happen. Numbers from it tell you nothing about release behavior. If you benchmark once in your first week and conclude Rust is slow, this was why.
Reaching for Box<dyn Fn> because delegates are one type. The C# habit is to type a variable as Func<T, R> and move on. The Rust equivalent of that habit allocates on every closure. Recognize it by seeing Box<dyn Fn...> in a signature that is only ever called with one closure, and fix it by taking impl Fn(...) or a generic F: Fn(...) parameter instead.
Collecting between every stage. .iter().map(...).collect::<Vec<_>>() followed by another .iter() is the mechanical translation of a LINQ chain that someone materialized with ToList for readability. In C# that costs one list. In Rust it costs an allocation and destroys the fusion that made the pipeline free in the first place. Chain the adapters and collect once, at the end.
Cloning to make a borrow error go away in a hot loop. Fine in cold code, deliberate in warm code, and a genuine performance bug in a loop. If the same .clone() runs per iteration, that is the signal to restructure rather than a cost of doing business.
Assuming LINQ is the slow part. Often it is not. Before rewriting a query, measure. Very often the allocation you are chasing is a string.Format or a serializer, and the LINQ chain is a rounding error next to a database round trip.
So when is it worth it
I would not port a healthy ASP.NET service to Rust. Modern .NET is genuinely fast, the ecosystem is deeper for line-of-business work, and a modest throughput gain almost never justifies a rewrite of something that already works.
Where I would reach for Rust:
- Something in the hot path of every request where tail latency matters more than throughput, and collection pauses are showing up in the p99.
- Something with a hard memory budget, such as an agent on every host, where resident set is the constraint.
- A library that has to be called from other languages, where shipping a runtime is not acceptable.
- CLI tools, where a single static binary with no runtime dependency is worth a lot.
- Anywhere you would otherwise write C or C++.
Where I would stay on .NET: CRUD services, anything dominated by database or network latency, teams without Rust experience under delivery pressure, and anything needing the enterprise integration surface that NuGet has and crates.io does not.
The interesting version of this decision is rarely all-or-nothing. Rust speaks the C ABI, so the realistic move is to take the one component that is actually hot, write that in Rust, and leave everything else where it is.
That path is short enough to show. On the Rust side, a cdylib crate called fastsum with one exported function:
#[unsafe(no_mangle)]
/// Computes a checksum; null or empty inputs return zero.
///
/// # Safety
/// For a non-null pointer and nonzero length, `ptr` must identify `len`
/// initialized bytes within one live allocation. The range must not wrap,
/// must be at most `isize::MAX` bytes, and must not be mutated during the call.
pub unsafe extern "C" fn checksum(ptr: *const u8, len: usize) -> u32 {
if ptr.is_null() || len == 0 {
return 0;
}
// SAFETY: the caller guarantees `ptr` points at `len` initialized bytes
// that stay valid and unwritten for the duration of this call.
let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
bytes
.iter()
.fold(2166136261u32, |h, b| (h ^ *b as u32).wrapping_mul(16777619))
}
And on the .NET side, the LibraryImport source generator, which writes the marshalling code at compile time instead of at run time and therefore works under Native AOT:
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
internal static partial class Native
{
[LibraryImport("fastsum")]
[UnmanagedCallConv(CallConvs = new[] { typeof(CallConvCdecl) })]
private static partial uint checksum(ref byte data, nuint len);
public static uint Of(ReadOnlySpan<byte> data) =>
data.IsEmpty ? 0 : checksum(ref MemoryMarshal.GetReference(data), (nuint)data.Length);
}
A ref parameter of a blittable type is pinned by the generated stub and handed over as a bare pointer, so MemoryMarshal.GetReference gets you from a span to that pointer with no copy and no marshalling layer. nuint is what lines up with Rust's usize. Note the small irony in the project file: the generator requires AllowUnsafeBlocks, so the safe-looking C# side of this boundary is also opting out of verification.
This is the boundary most teams actually adopt Rust across, and the unsafe block on the Rust side sits exactly on it, which is the subject of the rest of this chapter.
Get the next deep dive by email
New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.
You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.
Written by Zeeshan Adil
I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.