Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 182 ยท Memory and Performance

Measuring and Improving Performance

Learn how to measure C# performance honestly: Stopwatch pitfalls, counting operations and allocations, BenchmarkDotNet, and the common wins such as StringBuilder and sized collections.

"Premature optimization is the root of all evil" is one of the most quoted lines in programming, and the part people forget is what comes next: we should not pass up our opportunities in the critical 3% of code. The skill is knowing which 3% that is, and the only reliable way is to measure. Programmers guess wrong about bottlenecks all the time. A loop that looks scary takes a microsecond, and a harmless-looking line hits the database 10,000 times.

This lesson teaches a measuring mindset first and tricks second. You will see why a naive Stopwatch lies, how to use counts (operations and allocated bytes) as stable metrics that do not depend on your machine, how real benchmarking works with BenchmarkDotNet, and then a short list of changes that win most of the time: StringBuilder, pre-sized collections, fewer allocations and care with LINQ in hot loops. It connects to garbage collection, spans and boxing.

The rules of performance work

  1. Define the goal. "Faster" is not a goal. "The page renders in under 200 ms at the 95th percentile" is.
  2. Measure before changing. Find the real hot spot with a profiler (Visual Studio, Rider, dotnet-trace, dotnet-counters) or logging.
  3. Change one thing, measure again. Keep the change only if the numbers improve.
  4. Prefer algorithmic wins. Going from O(nยฒ) to O(n log n) beats any micro-trick. A Dictionary lookup instead of a list scan is worth more than saving a string allocation.
  5. Keep it readable unless the gain is large and measured.

Stopwatch, and why a single reading lies

System.Diagnostics.Stopwatch measures elapsed time. It is the right tool for a quick look, but one reading is untrustworthy for these reasons:

  • JIT compilation. The first call to a method includes the time to compile it. .NET also uses tiered compilation: code starts in a quick, unoptimized tier and is recompiled when it proves hot.
  • Cold caches and warm-up. The first run touches memory the CPU has not cached.
  • Noise. Other processes, power saving and the GC all add jitter. One run can easily differ from the next by 50% or more.
  • Dead code elimination. If a result is never used, an optimizing compiler may skip the work, and you measure nothing.
  • Debug builds are slower and not representative; always measure Release builds.

The next example is deliberately shaped so that its output is stable: it shows the structure of a decent manual timing (warm up, repeat, use the result) without printing the times, because they would differ on every machine and every run.

C# The shape of a manual timing

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.

Stopwatch.GetTimestamp plus Stopwatch.GetElapsedTime (.NET 7 and later) avoids allocating a Stopwatch object, which is nice for tiny measurements. In this tutorial we never quote timings from the sandbox, because they are not reproducible. Everything below uses counts instead.

Count operations, not milliseconds

Often the question is not "how fast is the machine" but "how much work does the algorithm do". Counting operations gives you the same answer on every computer and exposes the growth rate, which is what really matters at scale.

C# Counting comparisons: linear versus binary search

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.

One hundred thousand comparisons versus about seventeen (the second number is roughly the base-2 logarithm of the data size). No microbenchmark is needed to see which one wins, and doubling the data adds one step to the binary search but doubles the linear one.

Allocations as a metric

As the garbage collection lesson explained, allocation is cheap but not free, and every byte must eventually be collected. GC.GetAllocatedBytesForCurrentThread() gives an exact, repeatable number. Wrapping it in a tiny helper makes experiments easy:

C# A small allocation meter

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.

Repeated s += i creates a new, longer string every time, so total allocation grows quadratically with the number of pieces. StringBuilder appends into a growing buffer, and string.Join sizes its result in one go. For two or three pieces, plain concatenation or interpolation is perfectly fine; the compiler turns it into a single string.Concat.

Common wins

Pre-size collections

List<T>, Dictionary<K,V> and StringBuilder grow by allocating a bigger array and copying. If you know roughly how many items you will add, say so in the constructor.

C# Capacity growth in a List

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.

The list doubles its capacity (4, 8, 16, ...), so 1,000 items cause nine array allocations (the first at capacity 4, the last at 1,024), and every discarded array is garbage. With new List<int>(1_000) there is exactly one allocation.

Avoid LINQ in the hottest loops

LINQ is expressive and fast enough for the vast majority of code. But each operator can allocate an enumerator and delegate objects, and closures capture variables. In an inner loop that runs millions of times, a plain for or foreach is measurably cheaper. Show it with bytes:

C# LINQ versus a loop: allocated bytes

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.

The LINQ version allocates because Where creates an iterator object and the lambda captures limit, which needs a closure object; the loop needs neither. That is not a reason to ban LINQ. It is a reason to profile first and rewrite only the loops that prove hot. Newer .NET versions also made many LINQ operators allocation-free for arrays and lists, so measure on your target runtime.

Choosing the right data structure usually beats micro-tuning. list.Contains(x) in a loop is O(n) each time; a HashSet<T> makes it O(1). See sets and choosing collections.

Other solid habits

  • Cache results of expensive pure computations (see fast lookups).
  • Avoid work in loops that can happen once: move invariant calculations out, compile a Regex once into a static readonly field (regex).
  • Use async for I/O, not to speed up CPU work. Parallelism helps CPU-bound loops only with real cores; the sandbox here has one.
  • Batch I/O. One query returning 1,000 rows beats 1,000 queries. One buffered write beats a thousand tiny ones.
  • Use Span<T> for parsing hot paths (spans) and avoid boxing (boxing).

BenchmarkDotNet: the proper way

For serious comparisons, use the open-source BenchmarkDotNet NuGet package. It runs each method in a separate process, warms up the JIT, repeats until the results are statistically stable, subtracts overhead, prevents dead-code elimination, and reports memory allocations with the [MemoryDiagnoser] attribute. It needs NuGet and the dotnet CLI, so the following code is read-only and cannot run in our editor.

C#
// Read-only: needs the BenchmarkDotNet NuGet package and a Release build.
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<StringBenchmarks>();

[MemoryDiagnoser]
public class StringBenchmarks
{
    [Params(10, 1_000)]
    public int Count;

    [Benchmark(Baseline = true)]
    public string Concat()
    {
        var s = "";
        for (int i = 0; i < Count; i++) { s += i; }
        return s;
    }

    [Benchmark]
    public string Builder()
    {
        var sb = new StringBuilder();
        for (int i = 0; i < Count; i++) { sb.Append(i); }
        return sb.ToString();
    }
}
Terminal
# Read-only: what you would type on your machine
dotnet run -c Release
TEXT
# Read-only: the shape of the report (numbers vary with the machine)
| Method  | Count | Mean       | Ratio | Allocated |
|-------- |------ |-----------:|------:|----------:|
| Concat  | 1000  | ...        | 1.00  | ...       |
| Builder | 1000  | ...        | ...   | ...       |

The columns to read are Mean (time), Ratio against the baseline and Allocated (bytes per operation). Always run in Release, without a debugger attached.

A checklist before you optimize

Question If the answer is no
Do I have a measurable goal? Define one first
Did I find the hot spot with a profiler? Do not guess; profile
Is it an algorithm or data-structure problem? Fix that before micro-tuning
Did I measure in Release, after warm-up, several times? The numbers are not trustworthy
Is the faster code still readable and tested? Keep the clear version unless the gain is big

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is a single Stopwatch reading of a method's first call unreliable?

    The first execution pays for compiling the code, and tiered compilation recompiles hot code later. Warm up, repeat several times and ideally use a tool like BenchmarkDotNet.
  2. 2. Which metric gives the same answer on every machine?

    Counting operations or allocated bytes does not depend on hardware speed or background load, so it is repeatable and good for teaching and for regression tests.
  3. 3. What does new List<int>(1000) save compared with new List<int>() when you add 1000 items?

    An unsized list doubles its internal array several times, creating garbage. Passing the capacity allocates the array once.
  4. 4. What is the main reason to use BenchmarkDotNet instead of a hand-written Stopwatch loop?

    BenchmarkDotNet is designed to avoid the classic mistakes (JIT effects, noise, dead-code elimination) and reports allocated memory with MemoryDiagnoser. It still needs a Release build.
  5. 5. Where should you look first when a program is slow?

    Big-O improvements and avoiding repeated expensive work (I/O, queries) outweigh micro-optimizations. A profiler shows where the time actually goes.

Summary

  • Set a goal, measure with a profiler or benchmark, change one thing, measure again.
  • A single Stopwatch reading is unreliable (JIT, tiering, caches, noise, dead-code elimination). Warm up, repeat, use the result and measure Release builds.
  • Counting operations and allocated bytes (GC.GetAllocatedBytesForCurrentThread) gives stable, machine-independent evidence.
  • Reliable wins: better algorithms and data structures, StringBuilder for many appends, pre-sized collections, fewer allocations, and plain loops in proven hot paths.
  • BenchmarkDotNet (NuGet, read-only here) is the standard tool for trustworthy microbenchmarks, with [MemoryDiagnoser] for allocations.
  • Keep clear code unless a measurement justifies the complexity.

Next: Fast Lookups: SearchValues, FrozenDictionary and Caching