C# Reference ยท .NET, Tools and Concepts
C# performance tips
Practical C# and .NET performance advice: measure first, cut allocations, choose the right collection, use Span and StringBuilder, and avoid async pitfalls.
.NET is fast by default, and most programs never need tuning. When they do, the gains almost always come from three places: doing less work (a better algorithm or data structure), allocating less memory (less garbage-collector pressure), and not blocking threads. This page lists practical habits in that order.
The first rule is to measure before you change anything. Guessing wrongly wastes time and makes code harder to read. Use a profiler for whole programs and BenchmarkDotNet for small pieces.
// Quick but unreliable: a single Stopwatch run includes JIT warm-up var sw = System.Diagnostics.Stopwatch.StartNew(); Work(); Console.WriteLine(sw.ElapsedMilliseconds);
Try it
Timing output is not reproducible, so these demos compare work counts and allocations in a way that gives the same answer on every run. The first one counts how many comparisons a list lookup needs compared with a hash lookup.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Allocations are visible with GC.GetAllocatedBytesForCurrentThread(). The program prints only the comparison, not the byte counts, because exact sizes vary between runtimes.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
There is no syntax to learn; the tools and features below are where performance work happens.
| Technique | Use it for |
|---|---|
StringBuilder |
Building a string in a loop. |
Span<T>, ReadOnlySpan<T>, Memory<T> |
Slicing arrays and strings without copying. |
ArrayPool<T>.Shared |
Reusing large temporary buffers. |
struct and readonly struct |
Small value-like data in hot paths (avoid boxing). |
List<T>(capacity) |
Avoiding repeated array growth. |
Dictionary/HashSet |
Fast lookup by key instead of scanning a list. |
ValueTask<T> |
Async methods that usually finish synchronously. |
Parallel.ForEach, PLINQ |
CPU-bound work on many items. |
static lambdas, stackalloc |
Avoiding closure allocations and small heap arrays. |
| Source generators | Replacing reflection (JSON, regex, logging). |
Usage notes
- Algorithms beat micro-tuning. Going from O(n) to O(1) lookup, or avoiding a nested loop, outweighs any syntax trick.
- LINQ is fine until it is not. It is clear and fast enough for most code. In a measured hot loop, a plain
forover an array removes iterator and delegate overhead. - Avoid repeated enumeration. Calling
Count()or enumerating a deferred query twice runs it twice. Materialize withToList()when you need the data more than once. - Boxing hurts. Putting a value type into
objector a non-generic collection allocates (Boxing and structs). - Strings: use
string.Create, interpolated string handlers,StringComparison.Ordinalfor non-linguistic comparison, andSplitonly when you need all parts. - Async: never block with
.Result/.Wait()(thread-pool starvation); do not wrap synchronous CPU work inTask.Runinside a web handler just to look asynchronous; run independent I/O in parallel withTask.WhenAll. - Exceptions are slow for normal flow. Use
TryParseandTryGetValueinstead of catching. - GC: Server GC suits throughput on multi-core servers, workstation GC suits desktop apps. Large objects (85,000 bytes and up) go to the large object heap and are expensive to churn (Garbage collection).
- Release builds only. Benchmarks and production should use
-c Release; Debug builds are much slower. The runner on this site compiles with optimizations. - Do not optimize unread code. Readability is a feature; keep the fast version for the 5% that is measured.