Blazing Fast .NET Performance
[!WARNING]
Much of the advice here might not age well: as .NET evolves, old hacks and custom knobs may become obsolete or even detrimental. Apply only after careful consideration and testing. Revisit periodically to ensure continued relevance.
This skill focuses on optimizing .NET applications for maximum performance, providing tips, techniques, and best practices to achieve blazing-fast execution times. It targets .NET 10.0 and 11.0. Older versions have not been tested.
Contents
- Profiling and Performance Analysis
- dotnet-counters
- dotnet-trace
- Low-level profiling with Linux CODE0
- Popular low-level problems
- Inspecting JIT codegen
- Best practices for high-performance C# code
- Quick tips
- Strings and globalization
- Thread pool starvation
- Contention on shared state
- False sharing
- Safe vectorization (SIMD or SWAR)
- Generic specialization via static abstract members
- ASP.NET Core
- Hosting and logging
- JSON and response writing
- Routing and middleware
- Kestrel socket transport
- Beyond benchmarks
- Magic knobs to Tune .NET Performance
- NativeAOT-specific tuning
- General notes
Profiling and Performance Analysis
Start cheap and go deeper only when needed: counters (what kind of bottleneck?) → traces (where?) → perf and JIT disassembly.
Install the tools with:
dotnet tool install -g dotnet-counters
dotnet tool install -g dotnet-trace
dotnet tool install -g dotnet-stack
dotnet tool install -g dotnet-symbol
dotnet-counters
dotnet-counters is a low-overhead, first-level triage tool. Run it while the app is under load:
dotnet-counters monitor -p <pid> # System.Runtime counters by default
dotnet-counters monitor -p <pid> --counters System.Runtime,Microsoft.AspNetCore.Hosting,System.Net.Http
dotnet-counters collect -p <pid> --format csv -o counters.csv # save for post-processing
See the System.Runtime built-in metrics (.NET 9+) for what each counter means. Typical readings:
| Symptom | Counters | Next step |
| --- | --- | --- |
| Low CPU, rising latency | dotnet.thread_pool.queue.length grows, dotnet.thread_pool.thread.count keeps creeping up | Thread pool starvation |
| Throughput doesn't scale with cores | dotnet.monitor.lock_contentions rate | dotnet-trace --clrevents contention, Contention on shared state |
| High CPU, much of it in GC | dotnet.gc.pause.time, dotnet.gc.collections (gen2 share), dotnet.gc.heap.total_allocated rate | Allocations and GC |
| Unexplained slow requests | dotnet.exceptions rate | dotnet-trace --clrevents exception |
| Numbers still drifting | dotnet.jit.compiled_methods still growing | Not at steady state yet: warm up longer |
dotnet-trace
dotnet-trace collects EventPipe traces on any OS without root or a native profiler (managed frames only):
dotnet-trace collect -p <pid> --duration 00:00:00:10 # default profiles: dotnet-common + dotnet-sampled-thread-time
dotnet-trace collect -p <pid> --profile gc-verbose # GCs + sampled allocations: which types/stacks allocate
dotnet-trace collect -p <pid> --clrevents contention # lock contention events with stacks
dotnet-trace collect -p <pid> --providers Microsoft-Windows-DotNETRuntime:0x80000000000:4 # .NET 10+: randomized allocation sampling, cheaper than gc-verbose
dotnet-trace collect -- ./MyApp arg1 # trace from startup
dotnet-trace list-profiles
dotnet-trace report trace.nettrace topN -n 20 # top methods (exclusive) as plain text
dotnet-trace report trace.nettrace topN -n 20 --inclusive
dotnet-trace convert trace.nettrace --format Speedscope # open in https://www.speedscope.app
On Linux with kernel 6.4+ and root, dotnet-trace collect-linux (.NET 10+) records native, kernel and managed frames in one trace without the perf setup below.
For more tips on using dotnet-trace, refer to the dotnet-trace collection skill.
Low-level profiling with Linux `perf`
The instructions below are mostly for CoreCLR/JIT scenarios on Linux with the native perf tool. NativeAOT/R2R scenarios should presumably work as is, without perf inject.
Typically, the following environment variables need to be set in the context of the running application:
DOTNET_PerfMapEnabled=1
DOTNET_PerfMapStubGranularity=3
DOTNET_JitFramed=1
DOTNET_EnableWriteXorExecute=0
DOTNET_PerfMapEnabled has an overhead of its own: set it for the profiling run only, not for the runs you take throughput numbers from.
What to profile depends on the scenario. Typically it's steady-state performance, so wait until the process is properly warmed up (e.g. 1 minute), then attach and collect traces:
perf record -k 1 -g -F 3999 -p $PROCESS_PID -o perf.data -- sleep 5
Next, symbolize the collected JIT frames using perf inject:
perf inject --input perf.data --jit --output perfjit.data
Then use the resulting perfjit.data file as needed, e.g. to generate flame graphs or annotated asm:
# annotated asm & report:
perf report --input perfjit.data --no-children --percent-limit 1 --stdio > perf_report.txt
perf annotate --stdio2 -i perfjit.data --percent-limit 1 -M intel > perf.asm
# Generate flamegraph (svg)
git clone --depth 1 --quiet https://github.com/brendangregg/FlameGraph || true
perf script -i perfjit.data | ./FlameGraph/stackcollapse-perf.pl | ./FlameGraph/flamegraph.pl > flamegraph.svg
Now perf.asm contains the annotated assembly output for the hottest methods in your application. Keep in mind that sample attribution is imprecise ("skid"): the cost is often reported on an instruction shortly after the one that actually stalls (e.g. right after a slow load or division), so inspect the neighboring instructions too.
In case of missing symbols you may need to use dotnet-symbol to download the necessary debug symbols for .dll/.dylib/.so:
dotnet-symbol --symbols $PUBLISH_FOLDER/*.dll
dotnet-symbol --symbols $PUBLISH_FOLDER/*.so
All other perf-related techniques (e.g. c2c, branch profiling, cache misses) can be applied similarly, depending on the performance aspects you want to analyze.
For simple functions, create a self-contained console application that calls the function in an infinite loop. For BenchmarkDotNet, use the in-process toolchain (-i or [InProcess]) with a long iteration duration and a very large iteration count so it is clear which process to attach perf to.
Popular low-level problems
- Cache contention and false sharing in multi-threaded code. Fix with per-thread data and padding (see False sharing).
- Bounds checks not being elided by the JIT.
- Store-to-load forwarding stalls, e.g. writing a struct field by field and reading it back with a wider load.
- Bad data locality causing cache misses.
- Code alignment noise. Loop or branch placement, Intel JCC erratum - not something we can control, just to keep in mind when analyzing performance variations.
- GC's alignment is 8 bytes (64-bit), which might not be suitable for SIMD optimizations (e.g. AVX512 might penalize every load/store if misaligned since the cache line is 64 bytes).
Inspecting JIT codegen
These are diagnostic switches (not tuning knobs) and work with the shipped Release runtime:
DOTNET_JitDisasm="Test" # method list: 'Test', 'Program:Test', '*Test*', 'Program:*' (space-separated)
DOTNET_JitDisasmSummary=1 # list every jitted method with its tier
DOTNET_JitStdOutFile=/tmp/jit.txt # write JIT output to a file instead of stdout
DOTNET_JitDisasmDiffable=1 # stable output (no addresses) for before/after diffs
DOTNET_JitDisasmOnlyOptimized=1 # show only Tier-1/FullOpts code
^ might require MethodImplOptions.NoInlining on the method to ensure it gets JIT-compiled and not inlined away.
[!TIP]
Set them only for the app process, not for
dotnet run, which would also dump the SDK's own methods.
- A method is compiled several times as it tiers up. Judge the last version: header
; Tier1 code(or; Tier1-OSR code/; FullOpts code), ideally with; optimized using Dynamic PGO.; Tier0 codeand; Instrumented Tier0 codeare unoptimized. - BCL methods precompiled with ReadyToRun show up only once they get hot and are re-jitted at Tier1.
- NativeAOT: pass the same options to ILC, e.g.
<IlcArg Include="--codegenopt:JitDisasm=Test" />and<IlcArg Include="--codegenopt:JitStdOutFile=jit.txt" />. - Inlining decisions:
DOTNET_JitPrintInlinedMethodsneeds a Checked JIT. On the Release runtime, collect theMethodJitInliningSucceeded/MethodJitInliningFailedevents (with the reason) viadotnet-trace collect --providers Microsoft-Windows-DotNETRuntime:0x1000:5.
Best practices for high-performance C# code
[!IMPORTANT]
Only safe C# code is considered in these best practices. Unsafe code is highly discouraged and not covered here.
Quick tips
- Use source-generated System.Text.Json: pass generated
JsonTypeInfo<T>to avoid reflection-based metadata discovery and enable supported serialization fast paths. Preserve existing serialization options and behavior. - Use