The most expensive performance mistake is rewriting code before measuring the source of delay. A three-second response may come from sequential external calls or a poorly indexed query rather than a LINQ expression. Reliable optimization follows a strict order: define a target, profile the system, change one thing, and measure again.
Define a performance budget
“Make it fast” is not testable. A useful target might require the product-search endpoint to remain below 250 ms at p95 under normal load, keep errors below 0.5 percent, and use less than 600 MB per instance. Averages can hide users waiting in the tail, so track p95 and p99 as well.
Break down the complete request
A distributed trace should separate HTTP, application, cache, SQL, and external API time. If a request takes 820 ms and 610 ms is spent in SQL, removing a small controller allocation will not create a meaningful improvement. Start with the largest frequent cost.
A microbenchmark example
[MemoryDiagnoser]
public class SlugBenchmarks
{
private readonly string _title = "Faster .NET Through Measurement";
[Benchmark(Baseline = true)]
public string RegexVersion() =>
Regex.Replace(_title.ToLowerInvariant(), @"[^a-z0-9]+", "-");
[Benchmark]
public string GeneratedRegexVersion() =>
SlugRegex().Replace(_title.ToLowerInvariant(), "-");
[GeneratedRegex(@"[^a-z0-9]+")]
private static partial Regex SlugRegex();
}
BenchmarkDotNet handles warmup, repetition, and statistical reporting, but a microbenchmark represents only an isolated algorithm. Confirm the result with an end-to-end load test and production telemetry.
High-value checks
- Remove unnecessary
ToList(), boxing, and temporary strings only when the allocation profile identifies them. - Keep I/O paths asynchronous; blocking with
.Resultor.Wait()can exhaust threads. - Check N+1 queries, missing indexes, and unbounded result sets before polishing local code.
- Define invalidation and privacy boundaries before adding cache.
A repeatable workflow
- Select a metric tied to user impact and record a baseline.
- Profile with representative data and load.
- Form one hypothesis about the largest bottleneck.
- Make the smallest relevant change.
- Run benchmark, integration, and load tests.
- Use a canary release and revert if production evidence shows no gain.
Conclusion
Performance work is an evidence loop, not the art of writing code that looks fast. Budgets, profiles, small experiments, and remeasurement produce larger gains with less risk to readability and correctness.
0 Comments