Skip to content
Tutorials Center
My learning

Topics

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.

C#
// 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.

C# Choose the data structure

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.

C# Less garbage with StringBuilder and Span

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 for over an array removes iterator and delegate overhead.
  • Avoid repeated enumeration. Calling Count() or enumerating a deferred query twice runs it twice. Materialize with ToList() when you need the data more than once.
  • Boxing hurts. Putting a value type into object or a non-generic collection allocates (Boxing and structs).
  • Strings: use string.Create, interpolated string handlers, StringComparison.Ordinal for non-linguistic comparison, and Split only when you need all parts.
  • Async: never block with .Result/.Wait() (thread-pool starvation); do not wrap synchronous CPU work in Task.Run inside a web handler just to look asynchronous; run independent I/O in parallel with Task.WhenAll.
  • Exceptions are slow for normal flow. Use TryParse and TryGetValue instead 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.