# The trade Rust is actually making

> What a tracing garbage collector buys a C# program, what its pauses cost, and how Rust moves that same safety work to compile time, with the real price.

- Author: Zeeshan Adil (https://www.internalswithzee.com/about)
- Published: 2026-09-06
- Updated: 2026-11-21
- Source: https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/the-trade-rust-is-making

Chapter 1 of 16 of [Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers.md). Part I, Foundations.

Start here if you want to understand the trade before learning the syntax. By the end, you should be able to explain what the collector does for a C# program and what work Rust asks the programmer and compiler to do instead. The GC measurements are supporting evidence; you can skim them on a first read.

Both languages begin with the same problem: a program should not be able to access memory that is no longer valid.

In C or C++, you can free memory and then use it. You can keep a pointer to a stack frame that has returned. You can hand the same buffer to two threads and let them write to it. These are not exotic mistakes. They are the ordinary result of a large codebase and a bad afternoon, and they produce crashes, silent corruption, and a large share of security vulnerabilities.

The size of that share is unusually well documented, because three organizations with very different codebases went and counted.

Matt Miller of Microsoft's Security Response Center presented the numbers at BlueHat IL in 2019. Slide 11 of [the deck, which Microsoft publishes on GitHub](https://github.com/microsoft/MSRC-Security-Research/blob/master/presentations/2019_02_BlueHatIL/2019_01%20-%20BlueHatIL%20-%20Trends%2C%20challenge%2C%20and%20shifts%20in%20software%20vulnerability%20mitigation.pdf), says it plainly: roughly 70% of the vulnerabilities Microsoft addresses through a security update each year are memory safety issues, and the chart behind it shows that proportion holding roughly flat from 2006 to 2018.

The Chromium security team [reached the same number independently](https://www.chromium.org/Home/chromium-security/memory-safety/). Around 70% of their serious security bugs are memory unsafety, half of those are use-after-free specifically, and the analysis covers 912 high or critical severity bugs since 2015 in shipped Stable channel code. Same figure, different codebase, different engineering culture.

The Android data is the one that actually moves the argument, because it is a before and after rather than a snapshot. Android shifted new native development toward memory-safe languages, mostly Rust and Java or Kotlin, and left the old C++ alone except for bug fixes. In December 2022 the Android team [reported](https://security.googleblog.com/2022/12/memory-safe-languages-in-android-13.html) that the annual number of memory safety vulnerabilities had fallen from 223 in 2019 to 85 in 2022, and from 76% of Android's total vulnerabilities down to 35%. Two years later the [follow-up post](https://security.googleblog.com/2024/09/eliminating-memory-safety-vulnerabilities-Android.html) put the figure at 24% across six years, and made the mechanism explicit: vulnerabilities decay exponentially, the density of memory safety bugs is highest in new and recently modified code, and so the returns come from where new code is written rather than from rewriting old code.

These reports show that memory safety bugs have been a substantial problem across several large codebases. Android's trend is consistent with a change in development practice, but it doesn't isolate a single cause; its authors explicitly caution against treating correlation as causation.

C# solved this a long time ago, and it solved it the way most modern managed languages did. References are checked, arrays are bounds-checked, and a garbage collector decides when memory is no longer reachable and reclaims it. You stopped thinking about it because you were allowed to stop thinking about it.

## What a tracing collector actually buys

Be precise about what the CLR does for you, because Rust's pitch is not "you get memory safety". You already have that. The pitch is that you can keep it without the machinery, and to judge that you have to know what the machinery is doing.

A tracing collector buys four separate things, and they are usually discussed as one.

**Allocation gets cheap.** The runtime reserves a contiguous region and keeps a pointer to the next free address. Allocating is a pointer bump, which Microsoft's own [fundamentals doc](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals) describes as almost as fast as allocating from the stack. A general-purpose allocator has different bookkeeping and fast paths. The relative cost depends on the allocator, allocation pattern, and runtime, so measure rather than assuming a fixed gap.

**Lifetime becomes somebody else's global problem.** This is the big one, and it is easy to under-appreciate because you have never had to state it. When you write `return list;` in C#, you make no claim about how long that list lives, who else holds it, or when it dies. The question is answered later, globally, by tracing from roots. You never answer it locally, which is exactly why you can pass an object graph around a service without designing its lifetimes.

**Unreachable cycles can be collected.** A doubly linked list or an object that refers back to its owner can form a cycle. Plain reference counting cannot reclaim an unreachable cycle without help; tracing checks reachability from roots, so the cycle's shape alone does not keep it alive.

**Fragmentation stops being your problem.** The collector can compact survivors together and fix up the references, which keeps allocation on the fast path and keeps related objects near each other in memory. Not always, though. The plan phase decides per collection whether compacting is worth it and otherwise sweeps, and the large object heap is not compacted at all unless you ask for it. Fragmentation is managed for you rather than eliminated.

You pay for those four in three currencies. A runtime ships with your program. Collection traces the live object graph, which costs CPU and memory bandwidth proportional to how much live data you keep. And collection happens at times you do not choose.

## Generations, and where the pause comes from

The .NET collector is generational because most objects die young. Gen0 holds new objects, survivors get promoted to gen1 and then gen2, and gen0 and gen1 together are the ephemeral generations. Objects of 85,000 bytes or more skip all of that and go on the large object heap, which the docs describe as a physical generation 3 that is logically collected along with gen2.

Two mechanisms in that design are the ones Rust deletes, so carry them in your head.

The first is the allocation budget. [The CLR GC design document](https://github.com/dotnet/runtime/blob/main/docs/design/coreclr/botr/garbage-collection.md) in dotnet/runtime describes it as a size limit per generation that triggers a collection for that generation when exceeded, and says the budget is set mostly from the survival rate of that generation: high survival means a larger budget, on the theory that the next collection will then find a better ratio of dead to live. So how often you collect is your allocation rate divided by a threshold the runtime keeps retuning underneath you.

The second is the card table. A gen0 collection wants to avoid scanning gen2, but a gen2 object can hold a reference to a gen0 object, and that reference is a root. So the JIT emits a write barrier on reference-field assignments: the same document says that when the JIT helper sees an object in the ephemeral range, it sets the byte containing the card that represents the source location. During ephemeral collections the collector scans set cards instead of the whole old heap. That bookkeeping adds work to applicable reference writes even between collections; its exact cost depends on the runtime and the code being executed.

Now the part that matters for latency. The document lists the flow directly. A user thread runs out of allocation budget and triggers a collection, the collector calls `SuspendEE` to suspend managed threads, then mark, then plan, then relocate and compact or else sweep, then `RestartEE`. With server GC the work is spread across dedicated collector threads, typically one per logical processor, but the suspension is the same suspension. With background GC, which is the default, the gen2 marking and sweeping mostly run alongside your threads, and the flow calls `SuspendEE` twice rather than once: at the start to decide, and again at the end to finish marking. Ephemeral collections that fire while a background collection is running are foreground collections, and those are fully blocking.

That is why "concurrent collector" is misleading if you read it as "no pauses". Background GC makes the long gen2 pause mostly go away. It does not make suspension go away, and gen0 and gen1 collections are always blocking because they are supposed to be short.

**Definition: Soundness and completeness**

A static analysis is **sound** if it never accepts a program that violates the property it checks. It is **complete** if it accepts every program that satisfies the property.

For general properties of arbitrary programs, a perfect checker can be impossible to build: the underlying question may be undecidable. A sound but incomplete analysis rejects some programs that would have behaved safely. Its guarantee also depends on its assumptions and implementation; bugs in a compiler or unsound `unsafe` code can break those assumptions.

This is the most useful frame for your first month of Rust. When the borrow checker rejects code you believe is correct, the program may be safe in that particular situation, or you may have missed a real lifetime or aliasing bug. The compiler is saying the code does not satisfy its rules; use the error to examine both possibilities. Those are different sentences, and knowing which one you are hearing changes what you do next.

## Allocation rate against pause behavior

The fundamentals doc puts the relationship in one line: the intrusiveness of garbage collections, meaning both frequency and duration, is the result of the volume of allocations and the amount of survived memory on the managed heap. Two independent knobs, pushing on different things.

Allocation rate drives frequency. Survivor volume drives duration.

That split is why the cost lands in the tail rather than in the average. Here is the arithmetic on a deliberately simple model, and then what is wrong with the model.

Take a service at 5,000 requests per second with a mean service time of 2 ms. By Little's law there are 5000 times 0.002, so about 10 requests in flight at any instant. Say it triggers 20 gen0 collections per second at 0.4 ms each. I am inventing those two numbers so the arithmetic has something to work on. Measure your own with `dotnet-counters`.

Total collector time is 20 times 0.4 ms, which is 8 ms per second, or 0.8% of wall clock. On a throughput graph that is invisible. It sits inside the noise of a deploy.

Now estimate affected requests. If all ten in-flight requests depend on the paused managed threads, 20 pauses catch roughly 200 such requests per second. At 5,000 arrivals per second, about two more arrive during each 0.4 ms pause, adding roughly 40 per second in this simplified model. That is about 4.8% of requests potentially affected. The exact latency increase and the percentiles it changes depend on arrival timing, what each request is doing, and the rest of the latency distribution; the arithmetic alone cannot prove what happens to p99.

Then take a blocking gen2 compaction, one every 60 seconds at 30 ms. That window holds 300,000 requests. This time the in-flight count is not what dominates, because the pause is fifteen times longer than a request: arrivals during the pause queue behind it, and that is 5000 times 0.03, so 150 requests, plus the 10 already running. About 160 out of 300,000 is 0.053%. If those were the only affected requests and all became the slowest, they would occupy roughly the top 0.053% of that window, beginning around p99.947. A p99.9 value would not necessarily move; a finer percentile or a time-series maximum might reveal the pause. Real queueing and the existing latency distribution can change that result.

That model is deliberately simple. Several details can change the result in either direction, so use it to form a question, not to predict a percentile without measurements.

Pause length is not a constant. It tracks survivors, and survivors track load, so pauses get longer exactly when you have the least headroom. Queueing is not additive either. A 30 ms suspension does not simply add 30 ms to 160 requests, it creates a convoy that takes several service times to drain, so requests behind the pause are slow too. The heap configuration moves underneath you: DATAS, which adapts heap count to application size, [is enabled by default starting in .NET 9](https://learn.microsoft.com/en-us/dotnet/core/runtime-config/garbage-collector), and the same page notes that when a workload ramps from lighter to heavier, allocating threads can wait, because it takes a few collections before the heap count increases. And the allocator's own slow path blocks: a thread that needs a fresh allocation context and cannot get one waits, which is not a collection pause and will not show up in your pause metrics.

None of that is an argument against the CLR. It is an argument that the cost is real, it is structural, and it is invisible in exactly the metric most teams watch.

For an ASP.NET service talking to a database, the trade is almost always correct. I would not rewrite one in Rust to save allocations, and an ASP.NET Core project on .NET 9 already ships with `System.GC.Server` set to `true` in its generated `runtimeconfig.json`, which is the right default for that shape of work. The interesting question is what happens when the trade stops being correct.

A proxy or sidecar in front of every request, where p99.9 is a number in a contract and every service behind you inherits your pauses. An agent installed on 50,000 hosts, where the runtime's baseline resident memory gets multiplied by 50,000 and lands on a finance review. A library that has to be callable from Python, Node and Go, where shipping a second garbage collector inside somebody else's process is a non-starter. A binary that has to start in single-digit milliseconds because something forks it per event. Firmware with no room for a runtime at all.

## The compile-time alternative, in principle

Deleting the collector without going back to `malloc` and `free` has a known price. State it before Rust's rules arrive, because the rules are the price.

You need rules that determine who owns each value and when cleanup should run. Rust inserts destructor calls at defined drop points, commonly when an owner leaves scope; a reference's last use can end its borrow before that. This gives cleanup a predictable structure you can inspect. No tracing, no write barrier, no suspension.

That is a static analysis problem, and in full generality it is undecidable. So Rust does what engineers always do with an undecidable problem: restrict the language until the analysis becomes decidable, and reject the programs it cannot prove. Every value has exactly one owner. References never outlive what they point at. You never hold a mutable reference at the same time as any other reference to the same place. Those three rules are the restriction, they are the subject of the ownership and borrowing chapters, and everything else in Rust is downstream of them.

The shape of the payoff is something you already know, because C# has it in a weaker form. `using` and `IDisposable` are deterministic cleanup at a scope boundary. Rust's `Drop` is the same idea, except it is not opt-in. A value's destructor normally runs automatically at its drop point, so there is no separate `using` statement to remember. That is not an absolute guarantee: cycles of reference-counted values, `std::mem::forget`, and process termination can prevent destructors from running. Resource wrappers also determine what cleanup their `Drop` implementation actually performs.

**Definition: Memory safety**

Memory safety means a program cannot read or write memory it has no right to. That covers use-after-free, double free, dangling pointers, buffer overruns, and reading uninitialized memory.

It is not the same as being bug-free, and it is not the same as thread safety, although Rust happens to address both. A memory-safe program can still compute the wrong answer, deadlock, or leak. Leaking in particular is safe in Rust, and the standard library ships `std::mem::forget` as a perfectly ordinary safe function.

Managed C# normally relies on runtime checks and garbage collection for memory safety. Safe Rust uses its type system and library guarantees to enforce many of the same protections without a tracing collector. Both languages have escape hatches, and Rust's safe abstractions depend on any underlying `unsafe` code being sound.

So the trade is legible. C# spends run time and memory to buy you freedom from thinking about lifetime. Rust asks you to express more ownership decisions at compile time and avoids the cost of a tracing collector; its allocations, synchronization, checks, and other runtime work still have costs. Neither is free. The compiler arguing with you is the bill arriving early.

There is a second thing you get, and it surprises people more than the performance. Ownership, borrowing, and traits such as `Send` and `Sync` also constrain what safe Rust can share across threads. This prevents data races in sound safe code, though it doesn't prevent every concurrency bug. I will come back to that properly, but keep it in mind: it is not a separate feature bolted on. It falls out of ownership.

## What Rust costs, honestly

Four things, and the enthusiasts undersell all four.

**Compile times.** Rust builds can be slower than the C# edit-build loop, though the comparison depends on the projects and build settings. C# emits IL and hands the optimization work to the JIT at run time. Rust hands it to LLVM at build time, after monomorphizing every generic instantiation into its own copy of the code, so a heavily generic crate produces far more machine code than you wrote. Work moved to compile time is still work. You can watch the same bill arrive in .NET the moment you publish with Native AOT, which also does whole-program codegen ahead of time and also takes a long time about it. On top of that, the crate is the unit of compilation, so a small edit can trigger a lot of recompilation, and the [Cargo profiles reference](https://doc.rust-lang.org/cargo/reference/profiles.html) notes that incremental compilation applies only to workspace members and path dependencies, which means bumping a dependency version rebuilds that dependency from scratch. There are levers, and Nicholas Nethercote's [chapter on compile times](https://nnethercote.github.io/perf-book/compile-times.html) in the Rust Performance Book is the place to start, but expect the edit-build-test loop to be slower than you are used to.

**Ecosystem depth.** Raw counts are closer than the reputation suggests. In September 2026 the crates.io summary API reports 329,413 crates and the NuGet search API reports 484,504 packages. Both numbers move daily, and neither counts quality. Breadth is not the gap. Depth in the specific places .NET is deep is the gap: no first-party Microsoft-maintained SQL Server driver, no equivalent of EF Core with a decade of migrations tooling behind it, nothing like the ASP.NET Core identity stack, no WCF or SOAP story worth the name, no Office interop, and nothing resembling the ecosystem of dependency injection containers most enterprise .NET architecture assumes. Where Rust is deep is network services, parsers, CLI tooling, cryptography, embedded, and WebAssembly. If your work sits in the first list, take the gap seriously. It is not a matter of waiting a year.

**Async.** It is genuinely harder, and the Rust project says so out loud. When `async fn` in traits stabilized in Rust 1.75, the async working group's [announcement](https://blog.rust-lang.org/2023/12/21/async-fn-rpit-in-traits/) opened by saying that important features many users need were still missing, and noted that traits using `async fn` are not object-safe, which means they lack support for dynamic dispatch. The Reference has since renamed that property to [dyn compatibility](https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility), so you will meet both terms depending on how old the page is. Nothing in your `Task`-based instincts prepares you for a trait method you cannot put behind a `dyn`. There is a chapter on it later and it is long for a reason.

**A slower first month.** Not slower at typing. Slower at deciding. In C# you model data and the runtime handles the rest. In Rust you model data and then answer a second question for every field and every parameter: who owns this, and for how long. That is real design work, you have never had to do it explicitly, and for the first few weeks you will get it wrong and restructure. Anyone who tells you the learning curve is a myth has forgotten what week one felt like.

There is a fifth cost that is not technical at all. Hiring, team experience, and tooling matter too. Depending on your market, experienced Rust engineers may be harder to find, and your team may be more productive with the debugging and framework support it already knows. Those are reasons to evaluate a migration against the people and workload you actually have, not just a benchmark.

Next: [Reading Rust when you already know C#](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-syntax-for-csharp-engineers.md)
