I wanted a list of .NET performance fixes that go past "use async" and "add a cache", with the code for each fix. Most of the remaining cost hides in C# that looks free: a line that allocates 100 KB reads exactly like a line that allocates nothing.
In this article, I show you how to measure a .NET service first, then 11 hidden costs in allocations, library defaults, and runtime settings, each with the code that fixes it. I left the database out. I covered EF Core in 18 Entity Framework Core Mistakes.
How to measure .NET performance before you optimize

I don't optimize code that doesn't show up in a benchmark or a profile. The two tools below tell you which of the other 11 items to read.
1. Benchmarking with Stopwatch instead of BenchmarkDotNet
A Stopwatch loop says your new version is faster. You ship it, and production doesn't change. The loop measured the wrong thing: the first iterations ran before the JIT finished optimizing the code, and the loop never showed how much memory each call allocated.
BenchmarkDotNet runs warmup iterations, repeats the measurement until the result is stable, and with [MemoryDiagnoser] reports the bytes allocated per call.
[MemoryDiagnoser]
public class HeaderBenchmarks
{
private const string Header = "id=42;name=order;status=paid";
[Benchmark(Baseline = true)]
public int Split() => Header.Split(';').Length;
[Benchmark]
public int Span() => Header.AsSpan().Count(';') + 1;
}
// Program.cs
BenchmarkRunner.Run<HeaderBenchmarks>();Run it with dotnet run -c Release. The result table has Mean, Ratio, Gen0, and Allocated columns. On a hot path, I look at the Allocated column in BenchmarkDotNet before the time column. A method that allocates on every call costs you again later, when the garbage collector (GC) has to clean up, and the Mean column doesn't show that cost.
What to change. Put every "this is faster" claim into a BenchmarkDotNet class with [MemoryDiagnoser] before it goes into a PR, and keep the benchmark project in the repo.
2. Guessing in production instead of reading the runtime counters
A benchmark tells you about one method. In production, you need to know whether the GC, blocked threads, or something outside .NET slows the service. dotnet-counters shows that without a restart:
dotnet tool install --global dotnet-counters
dotnet-counters monitor --name MyApi --counters System.RuntimeBefore I change any code, I look at the GC and thread pool counters in dotnet-counters. Four of them point to most of the items in this article. The exact names differ a little between .NET versions (.NET 9 uses dotnet.gc.* and dotnet.thread_pool.*), but the meaning is the same:
| Counter | What a bad value looks like | Read |
|---|---|---|
| % time in GC | High and steady, not short spikes | Items 3–10 |
| Allocation rate | Grows much faster than the request rate | Items 3–10 |
| Gen 2 collections | Climbing steadily under normal load | Items 3 and 11 |
| Thread pool thread count and queue length | Threads keep climbing, queue grows, CPU stays low | Item 13 |
What to change. Run dotnet-counters against a loaded instance (staging under a load test, or one production pod) and write down the four values before you change anything. That's your baseline.
Reduce allocations and GC pressure in C#
Every allocation is cheap on its own. The cost comes later: the more you allocate, the more often the GC runs, and objects that survive long enough move to Gen 2, where a collection is the most expensive.
3. Large buffers that land on the Large Object Heap
.NET puts every object of 85,000 bytes or more on a separate heap, the Large Object Heap (LOH). The GC cleans the LOH only during a full Gen 2 collection, and by default it doesn't compact it, so the free space gets fragmented. A byte[] of 84,976 bytes already crosses the limit, because the array header counts too.
So a service that allocates a 100 KB buffer per request turns every request into future gen 2 work:
// Before: a new 100 KB array per request goes straight to the LOH
var buffer = new byte[100_000];
int read = await stream.ReadAsync(buffer);
// After: rent from a shared pool and give it back
byte[] buffer = ArrayPool<byte>.Shared.Rent(100_000);
try
{
int read = await stream.ReadAsync(buffer.AsMemory(0, 100_000));
Process(buffer.AsSpan(0, read));
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}Rent can return a bigger array than you asked for, so always work with the length you requested, not buffer.Length. And never touch the array after Return: another request may already own it.
MemoryStream hides the same problem: it doubles and copies its array as it grows, and ToArray() copies it once more. For large payloads, use Microsoft's RecyclableMemoryStream, which pools those buffers:
private static readonly RecyclableMemoryStreamManager Streams = new();
using var stream = Streams.GetStream();What to change. Search for new byte[ and MemoryStream on request paths. Move anything near or above 85,000 bytes to ArrayPool<T>.Shared or RecyclableMemoryStream, and return the buffer in a finally.
4. Allocations you don't see: closures, boxing, and string copies
Closures. A lambda that uses a local variable captures it. The compiler then creates an object to hold that variable and a delegate that points to it, on every call of the method:
// Allocates a closure and a delegate on every call: the lambda captures minTotal
decimal minTotal = GetMinTotal();
int count = orders.Count(o => o.Total > minTotal);
// No allocation: a plain loop
int count = 0;
foreach (var o in orders)
if (o.Total > minTotal) count++;The compiler caches a lambda that captures nothing. Mark it static (orders.Where(static o => o.IsPaid)), and the compiler stops anyone who later adds a captured variable.
Boxing. When a value type goes where an object or an interface is expected, .NET copies it into a new heap object. Passing an int to a method that takes object, or storing a struct in a variable typed as IComparable, boxes it every time.
String copies. a.ToLower() == b.ToLower() creates two new strings just to compare them. string.Equals(a, b, StringComparison.OrdinalIgnoreCase) compares in place and allocates nothing.
What to change. In methods that run per request or per item, replace capturing lambdas with loops or static lambdas, keep value types away from object parameters, and compare strings with a StringComparison overload. Outside hot paths, leave the LINQ alone: readability wins there.
5. Parsing with Substring and Split instead of Span<T>
Split allocates an array plus one new string for every part. Parsing a header like id=42;name=order;status=paid with Split(';') and then Split('=') creates about ten objects to read one number.
ReadOnlySpan<char> is a view over memory that already exists. Slicing a span moves two numbers (start and length) and copies no characters:
static int? ReadId(ReadOnlySpan<char> header)
{
while (!header.IsEmpty)
{
int end = header.IndexOf(';');
var pair = end < 0 ? header : header[..end];
header = end < 0 ? default : header[(end + 1)..];
int eq = pair.IndexOf('=');
if (eq > 0 &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; pair[..eq] is "id")
return int.Parse(pair[(eq + 1)..]);
}
return null;
}This version allocates nothing. int.Parse, Guid.Parse, and most other parsing APIs accept a span directly.
What to change. Use spans in parsers, formatters, and protocol code that runs per request. Note: a span lives only on the stack. You can't store it in a class field, capture it in a lambda, or keep it across an await. Use Memory<T> in those places.
6. Structs that copy themselves or compare with reflection
Structs avoid heap allocations, but two defaults can make them slower than a class.
A struct as a dictionary key. If a struct doesn't implement IEquatable<T>, Dictionary and HashSet fall back to ValueType.Equals. That method boxes both values, and when the struct has a reference-type field (a string, for example), it compares the fields through reflection. The default GetHashCode can also produce many identical hashes, so the dictionary calls Equals far more often than you expect. In one case Microsoft engineers described, inserting 1,000 elements into a set caused almost 500,000 calls to ValueType.Equals.
// Before: reflection and boxing on every key comparison
public struct OrderKey
{
public string Region;
public int Number;
}
// After: the compiler generates IEquatable<T>, Equals, and GetHashCode
public readonly record struct OrderKey(string Region, int Number);Defensive copies. When you call a method on a struct stored in a readonly field, or passed as an in parameter, the compiler can't be sure the method won't change the struct. So it copies the whole struct first, on every call:
public struct Interval
{
public double Min, Max;
public double Length() => Max - Min;
}
class Shape
{
private readonly Interval _bounds;
public double Size() => _bounds.Length(); // copies _bounds before the call
}Declare it as public readonly struct Interval, and the copy goes away, because the compiler now knows no method can change it.
What to change. Make every struct readonly unless it has to change, and use readonly record struct for any struct you put in a dictionary or a set. Turn on analyzer rules CA1815 (structs with the default equality) and IDE0250 (structs that can be readonly).
Fix library defaults that slow down .NET apps
The next four APIs do expensive setup work that should happen once, and the easy way to call them repeats it on every call.
7. A new JsonSerializerOptions on every call
System.Text.Json builds metadata for every type it serializes (property lists, converters, accessors) and caches it inside the JsonSerializerOptions instance. Create a new options object per call, and the cache starts empty every time:
// Before: rebuilds the metadata cache on every call (CA1869)
var json = JsonSerializer.Serialize(order,
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
// After: one instance for the whole app; it's thread-safe
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
var json = JsonSerializer.Serialize(order, Json);Copying an existing instance with new JsonSerializerOptions(existing) doesn't help either: the copy doesn't carry the cache. ASP.NET Core reuses its own options for request bodies, so look at your own calls: a cache wrapper, a message publisher, an HttpClient helper.
For hot paths, go one step further and generate the metadata at build time:
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(Order))]
internal partial class AppJsonContext : JsonSerializerContext { }
var json = JsonSerializer.Serialize(order, AppJsonContext.Default.Order);What to change. Search for new JsonSerializerOptions outside static fields and constructors of singletons, and turn on CA1869 to catch new ones. Add a JsonSerializerContext for the types you serialize the most. You need it anyway if you plan to use Native AOT (item 12).
8. Building a Regex on every call
new Regex(pattern) parses the pattern and builds a matcher before it matches anything. Do that inside a method, and every call pays for it. The static Regex.IsMatch(input, pattern) keeps a small cache, but it holds only 15 patterns by default, so a service with many patterns keeps rebuilding them. RegexOptions.Compiled makes matching faster and construction much slower.
Since .NET 7, the source generator builds the matcher at compile time:
// Before: parses the pattern on every call
bool ok = new Regex(@"^[A-Z]{2}-\d{6}$").IsMatch(code);
// After: the matcher is C# code generated at build time
public static partial class Patterns
{
[GeneratedRegex(@"^[A-Z]{2}-\d{6}$")]
public static partial Regex OrderCode();
}
bool ok = Patterns.OrderCode().IsMatch(code);You get matching speed close to RegexOptions.Compiled without its startup cost.
What to change. Move every fixed pattern to a [GeneratedRegex] method. Visual Studio suggests the change for you (analyzer SYSLIB1045). For patterns that run on user input, pass a timeout to the attribute, or use RegexOptions.NonBacktracking. Note: the generator doesn't generate code for NonBacktracking. It falls back to a cached regular Regex, which is still better than a new one per call.
9. Log calls that allocate when the log level is off
This line builds a string on every call, even in production where Debug logging is off:
_logger.LogDebug($"Order {order.Id} processed in {elapsedMs} ms");C# evaluates the arguments before the logger checks the level, so the string gets built and thrown away. The template version (LogDebug("Order {OrderId}…", order.Id, elapsedMs)) is better, but it still boxes the int and the long into an object[], and it parses the template at runtime.
The logging source generator fixes all three:
public static partial class Log
{
[LoggerMessage(Level = LogLevel.Debug,
Message = "Order {OrderId} processed in {ElapsedMs} ms")]
public static partial void OrderProcessed(ILogger logger, int orderId, long elapsedMs);
}
Log.OrderProcessed(_logger, order.Id, elapsedMs);The generated method checks IsEnabled first, takes typed parameters (no boxing), and parses the template at compile time. As a bonus, OrderId stays a separate field in your structured logs, which the interpolated string loses.
What to change. Move log calls on hot paths (per request, per message, per item) to [LoggerMessage] methods. Turn on CA1873 to find calls with expensive arguments. Leave startup and error logs as they are: they run rarely.
10. The wrong collection for the access pattern
List<T>.Contains checks every item until it finds a match. Inside a loop, that's every item times every item:
// Before: scans the whole list for every order
List<int> blocked = GetBlockedCustomerIds(); // say, 50,000 ids
var allowed = orders.Where(o => !blocked.Contains(o.CustomerId)).ToList();
// After: one hash lookup per order
HashSet<int> blocked = GetBlockedCustomerIds().ToHashSet();A List<T> created without a capacity doubles and copies its array as it grows, and a large one lands on the LOH (item 3) several times on the way. Pass the capacity when you know it: new List<OrderDto>(orders.Count).
For data you load once at startup and then only read (currency rates, feature flags, routing tables), .NET 8 added FrozenDictionary and FrozenSet. They take longer to build and are faster to read. In Microsoft's ASP.NET Core routing benchmark, lookups were 2.5–3.5 times faster than with Dictionary. I haven't compared FrozenDictionary with Dictionary on my own data, so I'd benchmark it before switching.
private static readonly FrozenDictionary<string, decimal> Rates =
LoadRates().ToFrozenDictionary();What to change. Look for .Contains, .Any(x => x.Id == …), and .First(x => x.Id == …) inside loops, and build a HashSet or Dictionary before the loop. Set the capacity when you know the size. More on picking a collection in the C# collections interview questions.
Tune the .NET runtime: GC mode, containers, and startup
11. A GC mode that doesn't match the container
ASP.NET Core apps use Server GC by default. Server GC creates one heap per CPU core and lets them grow large, because it assumes the process owns the machine. In a Kubernetes pod next to five other services, that takes far more memory than the app needs.
.NET 9 changed the default. With Server GC, it now turns on DATAS (Dynamic Adaptation To Application Sizes): the GC starts with one heap and adds heaps only when the load needs them. Microsoft measured it on a 48-core machine with the TechEmpower benchmarks: the working set dropped by more than 80%, and throughput dropped by 2–3%.
The second default to know: in a container with a memory limit, the GC caps its heap at 75% of that limit. You can change both in the project file or in runtimeconfig.template.json:
<PropertyGroup>
<ServerGarbageCollection>true</ServerGarbageCollection>
<GarbageCollectionAdaptationMode>1</GarbageCollectionAdaptationMode>
</PropertyGroup>
{
"configProperties": {
"System.GC.HeapHardLimitPercent": 80
}
}I'd leave the GC settings at their defaults until the counters show a problem. On .NET 9, DATAS is a good default for most services.
What to change. On .NET 8, try DATAS in staging and compare memory and p99 latency. On any version, check that your container memory limit leaves room for the 75% heap cap plus the native memory around it. If pods get OOM-killed while the GC heap looks small, the problem is outside the managed heap.
12. Paying for JIT compilation at startup in short-lived apps
A .NET app compiles each method to machine code the first time it calls it. A web API that runs for weeks pays this once. A function or job that runs for three seconds pays it on every start.
Two switches move that work to build time:
<PublishReadyToRun>true</PublishReadyToRun>
<PublishAot>true</PublishAot>ReadyToRun keeps the JIT, so hot methods still get recompiled with full optimizations. The cost is a bigger publish folder. Native AOT removes the JIT completely. That gives the fastest startup and the smallest memory, but it also removes dynamic PGO (profile-guided optimization), which is on by default since .NET 8 and lets the JIT tune hot code based on how it actually runs. Reflection-heavy libraries and runtime code generation don't work under Native AOT, so check the trimming warnings first.
I'd use Native AOT for short-lived jobs and serverless functions, and keep the JIT for long-running services.
Don't copy <TieredCompilation>false</TieredCompilation> from old performance guides. Dynamic PGO needs tiered compilation, so turning it off usually makes a long-running service slower.
What to change. For functions, jobs, and CLI tools, publish with ReadyToRun first, since it needs no code changes. Move to Native AOT when the startup still matters, and your libraries support it. For long-running services, keep the defaults.
13. Thread pool starvation: high latency with low CPU
The symptom is confusing: requests take seconds, but the CPU sits at 20%. Usually some code blocks a thread pool thread while it waits for I/O:
// Holds a thread pool thread until the HTTP call finishes
var user = _http.GetFromJsonAsync<User>(url).Result;Under load, every request holds a thread like this; the pool runs out of free threads, and new work waits in the queue. The pool adds threads only gradually, so the queue grows faster.
dotnet-counters shows the pattern from item 2: the thread count climbs slowly and steadily, the queue length grows, and CPU stays far below 100%. Microsoft's guidance: if the thread count settles at more than about three times the number of CPU cores, some code is blocking threads. To find it, run dotnet-stack report --process-id <pid> and look for many threads stuck in Task.Wait, .Result, or GetResult.
What to change. You have three options, in this order. Make the call path async end to end (await instead of .Result), so the thread goes back to the pool while it waits. If a sync API forces you to block (an old library, a sync interface you can't change), keep that blocking code off the request path, or limit how many calls run at once. Raise ThreadPool.SetMinThreads only as a stopgap while you fix the blocking call, because it hides the problem and doesn't remove it. More on how the thread pool and async work together in the C# async and parallel programming interview questions.
Comments (0)