C# performance and measurement
Measure slow work, improve the real bottleneck, and confirm the change helped.
Chapter goal: Measure slow work, improve the real bottleneck, and confirm the change helped.
Simple explanation
Performance asks how much time and memory code uses. Measure first, then improve the part that is actually slow.
In C#, this chapter is about reducing unnecessary work without sacrificing correctness or clarity. Start with the idea above. Then connect each symbol to a value or action in the example.
Do not try to remember every symbol. First ask what data the program has, what it does with that data, and what result it creates. Technical words become easier when you connect them to those three questions.
Why this topic is important
Performance affects usability, battery, server cost, and how many users a system can support. In C#, the syntax may look different from other languages, but the thinking skill transfers: name the data, choose the right operation, and make the next step obvious.
When to use it
Optimize after measurements show slow rendering, repeated queries, heavy loops, memory growth, or blocked input.
Example code
var cache = new Dictionary<int, int>();
int SlowSquare(int n) {
if (cache.TryGetValue(n, out int cached)) return cached;
int result = n * n;
cache[n] = result;
return result;
}
var stopwatch = Stopwatch.StartNew();
SlowSquare(4);
SlowSquare(4); // second call reads the cache instead of repeating the work
Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds}ms");
Line-by-line explanation
var cache = new Dictionary<int, int>();— This stores or updatescache. The value on the right is worked out first, then saved under that name.int SlowSquare(int n) {— This line supports one focused piece of application logic. Read it together with the block directly around it.if (cache.TryGetValue(n, out int cached)) return cached;— This checks a true-or-false condition. The controlled block runs only when that condition is true.int result = n * n;— This stores or updatesresult. The value on the right is worked out first, then saved under that name.cache[n] = result;— This stores or updatescache[n]. The value on the right is worked out first, then saved under that name.return result;— This sends a result back to the code that called the function. Returning is different from printing.var stopwatch = Stopwatch.StartNew();— This stores or updatesstopwatch. The value on the right is worked out first, then saved under that name.SlowSquare(4);— This line supports one focused piece of application logic. Read it together with the block directly around it.SlowSquare(4); // second call reads the cache instead of repeating the work— This line supports one focused piece of application logic. Read it together with the block directly around it.Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds}ms");— This is the visible output line. It shows the final value after the earlier work is complete.
What the output means
The measured result depends on the input size; compare measurements before and after a change.
The output is evidence that the program followed the instructions. If your result is different, read from the first line and write down how each value changes. That is debugging, not failure.
Mistake example
var cache = null; // optimization is attempted without measuring the slow work
int SlowSquare(int n) {
if (cache.TryGetValue(n, out int cached)) return cached;
int result = n * n;
cache[n] = result;
return result;
}
var stopwatch = Stopwatch.StartNew();
SlowSquare(4);
SlowSquare(4); // second call reads the cache instead of repeating the work
Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds}ms");
This version intentionally shows how optimization is attempted without measuring the slow work. The changed assignment stores a missing value, or a required line is removed, so later code cannot complete its job safely.
Fixed version
var cache = new Dictionary<int, int>();
int SlowSquare(int n) {
if (cache.TryGetValue(n, out int cached)) return cached;
int result = n * n;
cache[n] = result;
return result;
}
var stopwatch = Stopwatch.StartNew();
SlowSquare(4);
SlowSquare(4); // second call reads the cache instead of repeating the work
Console.WriteLine($"Took {stopwatch.ElapsedMilliseconds}ms");
The corrected version restores the real value or required operation. It fixes the chapter-specific problem: optimization is attempted without measuring the slow work.
Common mistakes
- Optimizing code that is not slow.
- Hiding stale data behind caching.
- Measuring only on a powerful development machine.
Warning: Change one part at a time. If you change many lines together, it becomes harder to learn which change caused the result.
Real use cases
- Reduce unnecessary widget rebuilds.
- Index a database query.
- Avoid repeated work inside a game loop.
Practice exercise
- Identify repeated work.
- Measure before changing it.
- Explain the readability trade-off of the optimization.
Tip: If the exercise feels too large, complete only steps 1 to 3. Small working code teaches more than a large unfinished project.
Mini quiz
- What measurement proves the code is slow?
- Which work is repeated unnecessarily?
- What could caching make stale?
How to read AI-generated code
Do not copy AI code first. Read it like a detective. Find the data, follow the changes, and locate the final output. Ask AI to explain a line only after you have made your own guess.
- What data goes in?
- What values are stored?
- What calculation or decision happens?
- What is printed, displayed, saved, or returned?
- What can go wrong?
- Can you rename one value and still explain the code?
Language reading check
Find the program entry point, follow function calls one at a time, and keep track of each value's type. Do not jump into a class or helper until you know who calls it.
Before you move on
- I can explain this topic in my own words.
- I can read the small example without AI.
- I can change the example and predict the new result.
- I can find and fix one simple mistake.
- I can name one real project that uses this idea.
Next topic
Next, learn deployment and release. Before opening it, explain this chapter out loud in under one minute.
Open the interactive lesson →