Analyzing Dotnet Performance
.NET (Microsoft)OfficialPublished by .NET (Microsoft)
- Skill
- Review and audit
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a systematic approach to identifying performance bottlenecks in C# and .NET applications. It scans code for approximately 50 known anti-patterns across critical areas including asynchronous programming, memory management, string handling, collections, LINQ, regex, serialization, and I/O. By applying tiered severity classifications, it helps developers prioritize optimizations for hot paths and allocation-heavy code, ensuring that performance improvements are data-driven and actionable.
What it does
- Scans C# source code for performance anti-patterns using pattern-specific recipes.
- Categorizes findings by severity (Critical, Moderate, Info) to guide remediation efforts.
- Provides concrete, actionable fixes for identified performance issues.
- Supports tiered scan depths from critical-only to comprehensive analysis.
- Performs cross-file consistency checks to identify systemic optimization opportunities.
- Generates a structured report with a summary table and clear evidence for each finding.
When to use it
- During code reviews to identify performance optimization opportunities.
- When auditing hot paths for inefficient allocation patterns.
- As a pre-release check to systematically scan for known performance anti-patterns.
- To obtain a second-opinion analysis after manual performance tuning.
Advantages
- Reduces manual effort in identifying common .NET performance pitfalls.
- Prioritizes findings based on impact, focusing effort on hot paths.
- Provides clear, actionable guidance rather than just flagging issues.
- Scalable analysis from critical-only checks to full codebase audits.
- Helps prevent common performance regressions in .NET applications.
Usage examples
- “Scan my current directory for .NET performance anti-patterns using standard depth.”
- The agent will execute the standard scan, checking for async, memory, string, collection, LINQ, and I/O patterns, then output a prioritized list of findings with fixes.
- “Analyze the file 'DataProcessor.cs' for critical performance issues only.”
- The agent will perform a focused scan on the specified file, reporting only critical patterns like deadlocks or major regressions.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/dotnet/analyzing-dotnet-performance/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip analyzing-dotnet-performance.zip -d .agents/skills
Documentation by .NET (Microsoft)
.NET Performance Patterns
Scan C#/.NET code for performance anti-patterns and produce prioritized findings with concrete fixes. Patterns sourced from the official .NET performance blog series, distilled to customer-actionable guidance.
When to Use
Reviewing C#/.NET code for performance optimization opportunities
Auditing hot paths for allocation-heavy or inefficient patterns
Systematic scan of a codebase for known anti-patterns before release
Second-opinion analysis after manual performance review
When Not to Use
Algorithmic complexity analysis — this skill targets API usage patterns, not algorithm design
Code not on a hot path with no performance requirements — avoid premature optimization
Inputs
| Input | Required | Description |
|---|---|---|
| Source code | Yes | C# files, code blocks, or repository paths to scan |
| Hot-path context | Recommended | Which code paths are performance-critical |
| Target framework | Recommended | .NET version (some patterns require .NET 8+) |
| Scan depth | Optional | critical-only, standard (default), or comprehensive |
Workflow
Step 1: Load Critical Reference
Resolve bundled paths from the directory that contains this SKILL.md, not from the user's workspace. Load this reference file first:
references/critical-patterns.md
If a direct read fails, list this skill's references/ directory once and retry only when the listing shows the expected file. Do not use workspace file or text search to locate the skill installation.
Step 2: Detect Code Signals and Select Topic Recipes
Scan the code for signals that indicate which pattern categories to check. Use the ## Detection section from the critical reference when available and the inline recipes in Step 3 for initial signal detection.
After detecting signals, load only the topic-specific references selected by scan depth:
critical-only: No additional references (use onlycritical-patterns.md)standard(default): Load references matching detected signals from this list:references/async-patterns.md— async/Task/ValueTask signalsreferences/memory-and-strings.md— Span/Memory/string allocation signalsreferences/regex-patterns.md— Regex signalsreferences/collections-and-linq.md— Dictionary/List/LINQ signalsreferences/io-and-serialization.md— JsonSerializer/HttpClient/Stream signalsreferences/structural-patterns.md— always loaded (unsealed classes checked regardless)
comprehensive: Load all six topic-specific references above
For coverage reporting, the selected references are references/critical-patterns.md plus only the topic-specific references selected above. If any selected reference remains unavailable after retry, use the inline recipes in Step 3 for the missing coverage. Include Reference coverage: reduced; unavailable: <paths>; used inline recipes for missing references. in the final report, with <paths> replaced by the missing relative paths of the selected references only.
Use the ## Detection sections from loaded reference files and the inline recipes in Step 3 for categories whose reference files are unavailable.
| Signal in Code | Topic |
|---|---|
async, await, Task, ValueTask | Async patterns |
Span<, Memory<, stackalloc, ArrayPool, string.Substring, .Replace(, .ToLower(), += in loops, params | Memory & strings |
Regex, [GeneratedRegex], Regex.Match, RegexOptions.Compiled | Regex patterns |
Dictionary<, List<, .ToList(), .Where(, .Select(, LINQ methods, static readonly Dictionary< | Collections & LINQ |
JsonSerializer, HttpClient, Stream, FileStream | I/O & serialization |
Always check structural patterns (unsealed classes) regardless of signals.
Scan depth controls scope:
critical-only: Only critical patterns (deadlocks, >10x regressions)standard(default): Critical + detected topic patternscomprehensive: All pattern categories
Step 3: Scan and Report
For files under 500 lines, read the entire file first — you'll spot most patterns faster than running individual grep recipes. Use grep to confirm counts and catch patterns you might miss visually.
For each relevant pattern category, run the detection recipes below. Report exact counts, not estimates.
Core scan recipes (run these when reference files aren't available):
# Strings & memory
grep -n '\.IndexOf(\"' FILE # Missing StringComparison
grep -n '\.Substring(' FILE # Substring allocations
grep -En '\.(StartsWith|EndsWith|Contains)\s*\(' FILE # Missing StringComparison
grep -n '\.ToLower()\|\.ToUpper()' FILE # Culture-sensitive + allocation
grep -n '\.Replace(' FILE # Chained Replace allocations
grep -n 'params ' FILE # params array allocation
# Collections & LINQ
grep -n '\.Select\|\.Where\|\.OrderBy\|\.GroupBy' FILE # LINQ on hot path
grep -n '\.All\|\.Any' FILE # LINQ on string/char
grep -n 'new Dictionary<\|new List<' FILE # Per-call allocation
grep -n 'static readonly Dictionary<' FILE # FrozenDictionary candidate
# Regex
grep -n 'RegexOptions.Compiled' FILE # Compiled regex budget
grep -n 'new Regex(' FILE # Per-call regex
grep -n 'GeneratedRegex' FILE # Positive: source-gen regex
# Structural
grep -n 'public class \|internal class ' FILE # Unsealed classes
grep -n 'sealed class' FILE # Already sealed
grep -n ': IEquatable' FILE # Positive: struct equalityRules:
Run every relevant recipe for the detected pattern categories
Emit a scan execution checklist before classifying findings — list each recipe and the hit count
A result of 0 hits is valid and valuable (confirms good practice)
If reference files were loaded, also run their
## Detectionrecipes
Verify-the-Inverse Rule: For absence patterns, always count both sides and report the ratio (e.g., "N of M classes are sealed"). The ratio determines severity — 0/185 is systematic, 12/15 is a consistency fix.
Step 3b: Cross-File Consistency Check
If an optimized pattern is found in one file, check whether sibling files (same directory, same interface, same base class) use the un-optimized equivalent. Flag as 🟡 Moderate with the optimized file as evidence.
Step 3c: Compound Allocation Check
After running scan recipes, look for these multi-allocation patterns that single-line recipes miss:
Branched
.Replace()chains: Methods that call.Replace()across multipleif/elsebranches — report total allocation count across all branches, not just per-line.Cross-method chaining: When a public method delegates to another method that itself allocates intermediates (e.g., A calls B which does 3 regex replaces, then A calls C), report the total chain cost as one finding.
Compound
+=with embedded allocating calls: Lines likeresult += $"...{Foo().ToLower()}"are 2+ allocations (interpolation + ToLower + concatenation) — flag the compound cost, not just the.ToLower().string.Formatspecificity: Distinguish resource-loaded format strings (not fixable) from compile-time literal format strings (fixable with interpolation). Enumerate the actionable sites.
Step 4: Classify and Prioritize Findings
Assign each finding a severity:
| Severity | Criteria | Action |
|---|---|---|
| 🔴 Critical | Deadlocks, crashes, security vulnerabilities, >10x regression | Must fix |
| 🟡 Moderate | 2-10x improvement opportunity, best practice for hot paths | Should fix on hot paths |
| ℹ️ Info | Pattern applies but code may not be on a hot path | Consider if profiling shows impact |
Prioritization rules:
If the user identified hot-path code, elevate all findings in that code to their maximum severity
If hot-path context is unknown, report 🔴 Critical findings unconditionally; report 🟡 Moderate findings with a note: "Impactful if this code is on a hot path"
Never suggest micro-optimizations on code that is clearly not performance-sensitive
Scale-based severity escalation: When the same pattern appears across many instances, escalate severity:
1-10 instances of the same anti-pattern → report at the pattern's base severity
11-50 instances → escalate ℹ️ Info patterns to 🟡 Moderate
50+ instances → escalate to 🟡 Moderate with elevated priority; flag as a codebase-wide systematic issue
Always report exact counts (from scan recipes), not estimates or agent summaries.
Step 5: Generate Findings
Keep findings compact. Each finding is one short block — not an essay. Group by severity (🔴 → 🟡 → ℹ️), not by file.
Format per finding:
#### ID. Title (N instances)
**Impact:** one-line impact statement
**Files:** file1.cs:L1, file2.cs:L2, ... (list locations, don't build tables)
**Fix:** one-line description of the change (e.g., "Add `StringComparison.Ordinal` parameter")
**Caveat:** only if non-obvious (version requirement, correctness risk)Rules for compact output:
No ❌/✅ code blocks for trivial fixes (adding a keyword, parameter, or type change). A one-line fix description suffices.
Only include code blocks for non-obvious transformations (e.g., replacing a LINQ chain with a foreach loop, or hoisting a closure).
File locations as inline comma-separated list, not a table. Use
File.cs:L42format.No explanatory prose beyond the Impact line — the severity icon already conveys urgency.
Merge related findings that share the same fix (e.g., all
.ToLower()calls go in one finding, not split by file).Positive findings in a bullet list, not a table. One line per pattern:
✅ Pattern — evidence.
End with a summary table and disclaimer:
| Severity | Count | Top Issue |
|----------|-------|-----------|
| 🔴 Critical | N | ... |
| 🟡 Moderate | N | ... |
| ℹ️ Info | N | ... |
> ⚠️ **Disclaimer:** These results are generated by an AI assistant and are non-deterministic. Findings may include false positives, miss real issues, or suggest changes that are incorrect for your specific context. Always verify recommendations with benchmarks and human review before applying changes to production code.Validation
Before delivering results, verify:
[ ] All critical patterns were checked (from reference files or inline recipes)
[ ] Topic-specific recipes run only when matching signals detected
[ ] Each finding includes a concrete code fix
[ ] Scan execution checklist is complete (all recipes run)
[ ] Summary table included at end
Common Pitfalls
| Pitfall | Correct Approach |
|---|---|
Flagging every Dictionary as needing FrozenDictionary | Only flag if the dictionary is never mutated after construction |
Suggesting Span<T> in async methods | Use Memory<T> in async code; Span<T> only in sync hot paths |
| Reporting LINQ outside hot paths | Only flag LINQ in identified hot paths or tight loops; LINQ is acceptable in code that runs infrequently. Since .NET 7, LINQ Min/Max/Sum/Average are vectorized — blanket bans on LINQ are misguided |
Suggesting ConfigureAwait(false) in app code | Only applicable in library code; not primarily a performance concern |
Recommending ValueTask everywhere | Only for hot paths with frequent synchronous completion |
Flagging new HttpClient() in DI services | Check if IHttpClientFactory is already in use |
Suggesting [GeneratedRegex] for dynamic patterns | Only flag when the pattern string is a compile-time literal |
Suggesting CollectionsMarshal.AsSpan broadly | Only for ultra-hot paths with benchmarked evidence; adds complexity and fragility |
Suggesting unsafe code for micro-optimizations | Avoid unsafe except where absolutely necessary — do not recommend it for micro-optimizations that don't matter. Safe alternatives like Span<T>, stackalloc in safe context, and ArrayPool cover the vast majority of performance needs |
Files
- ATTRIBUTION.mdAdded by AutoGineer867 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md12.4 KiB
- references/async-patterns.md2.9 KiB
- references/collections-and-linq.md7.6 KiB
- references/critical-patterns.md6.6 KiB
- references/io-and-serialization.md3.6 KiB
- references/memory-and-strings.md5.7 KiB
- references/regex-patterns.md3.2 KiB
- references/structural-patterns.md1.6 KiB
references/memory-and-strings.md
Memory & String Patterns
Use ReadOnlySpan<byte> for Constant Byte Data
🟡 DO assign constant byte arrays to ReadOnlySpan<byte> | .NET 5+
❌
byte[] data = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F };✅
ReadOnlySpan<byte> data = [0x48, 0x65, 0x6C, 0x6C, 0x6F];
ReadOnlySpan<int> primes = [2, 3, 5, 7, 11, 13];Impact: ~100x faster access than static byte[] field, zero allocation.
Use stackalloc for Small Temporary Buffers
🟡 DO use stackalloc for small, fixed-size temporary buffers | .NET Core+
❌
char[] buffer = new char[64];
guid.TryFormat(buffer, out int written);✅
Span<char> buffer = stackalloc char[64];
guid.TryFormat(buffer, out int written);Impact: Zero heap allocation, no GC pressure, instant alloc/dealloc.
Use Span.TryWrite for Allocation-Free Interpolation
🟡 DO use MemoryExtensions.TryWrite to format into Span<char> buffers | .NET 6+
❌
string formatted = $"Date: {dt:R}";
destination.Write(formatted);✅
Span<char> buffer = stackalloc char[64];
buffer.TryWrite($"Date: {dt:R}", out int charsWritten);Impact: Zero heap allocation for formatting operations.
Use Span.Split() for Zero-Allocation Splitting
🟡 DO use MemoryExtensions.Split for allocation-free string splitting | .NET 9+
❌
string[] parts = input.Split(',');✅
foreach (Range range in input.AsSpan().Split(','))
{
ReadOnlySpan<char> segment = input.AsSpan(range);
}Impact: 208 bytes → 0 bytes per split, 2x faster.
Use UTF8 String Literals (u8 suffix)
🟡 DO use the u8 suffix for compile-time UTF8 ReadOnlySpan<byte> | .NET 7+
❌
byte[] header = Encoding.UTF8.GetBytes("Content-Type");✅
ReadOnlySpan<byte> header = "Content-Type"u8;Impact: 17ns → 0.006ns — eliminates runtime transcoding entirely.
Use ReadOnlySpan<char> Pattern Matching with switch
🟡 DO use switch on ReadOnlySpan<char> for allocation-free string matching | C# 11+
❌
switch (attr.Value.Trim()) { case "preserve": /* ... */ break; }✅
switch (attr.Value.AsSpan().Trim())
{
case "preserve": return Preserve;
case "default": return Default;
}Impact: Eliminates string allocation from Trim() in switch-based dispatch.
Use params ReadOnlySpan<T> to Eliminate Array Allocations
🟡 DO add params ReadOnlySpan<T> overloads to library methods | C# 13 / .NET 9+
❌
public static void Log(params string[] messages) { /* ... */ }
Log("Starting", "Processing", "Done");✅
public static void Log(params ReadOnlySpan<string> messages) { /* ... */ }
Log("Starting", "Processing", "Done");Impact: Eliminates params array allocation. E.g., Path.Join with 5+ segments saves 64 bytes per call.
Avoid Chained String-Returning Operations
🟡 AVOID chains of 3+ string-returning method calls that each allocate intermediates | .NET Core+
Pattern 1: Chained .Replace() calls
❌
string result = input.Replace("a", "b").Replace("c", "d").Replace("e", "f");✅
var sb = new StringBuilder(input.Length);
// single pass replacing all patternsPattern 2: Chained Regex.Replace() calls
❌
public static string Underscore(this string input) =>
Regex3.Replace(Regex2.Replace(Regex1.Replace(input, "$1_$2"), "$1_$2"), "_").ToLower();✅
return string.Create(totalLength, state, (span, s) => { /* write directly */ });Pattern 3: += string concatenation in loops
❌
string result = "";
foreach (var part in parts)
result += separator + part;✅
var sb = new StringBuilder();
foreach (var part in parts)
sb.Append(separator).Append(part);
return sb.ToString();Impact: Eliminates N-1 intermediate string allocations per chain. For += in loops, eliminates O(n²) total allocation.
Cache char.ToString() for Known Character Sets
🟡 DO cache char.ToString() results when the set of characters is small and known | .NET Core+
❌
return symbol.ToString();
foreach (var prefix in UnitPrefixes)
input = input.Replace(prefix.Value.Name, prefix.Key.ToString());✅
private static readonly FrozenDictionary<char, string> s_charStrings =
new Dictionary<char, string>
{
['k'] = "k", ['M'] = "M", ['G'] = "G",
}.ToFrozenDictionary();
return s_charStrings[symbol];Impact: Eliminates one string allocation per char.ToString() call. Significant when called in loops or on hot paths.
Detection
Scan recipes for memory and string anti-patterns. Run these and report exact counts.
# .ToLower()/.ToUpper() without culture parameter (allocates + culture-sensitive)
grep -rn --include='*.cs' -E '\.(ToLower|ToUpper)\(\)' --exclude-dir=bin --exclude-dir=obj . | wc -l
# Chained .Replace( calls (3+ on one line — intermediate string allocations)
grep -rn --include='*.cs' '\.Replace(.*\.Replace(.*\.Replace(' --exclude-dir=bin --exclude-dir=obj . | wc -l
# params in method signatures (array allocation per call)
grep -rn --include='*.cs' 'params ' --exclude-dir=bin --exclude-dir=obj . | wc -l
# LINQ on strings — .All/.Any on IEnumerable<char> (replace with foreach loop)
grep -rn --include='*.cs' -E '\.(All|Any)\(char\.' --exclude-dir=bin --exclude-dir=obj . | wc -lPatterns Requiring Manual Review
Boxing via string.Format: Can't determine argument types from grep — needs type analysis
+=string concatenation in loops:+=matches all types (int, list, event, string) — needs type context to confirm stringchar.ToString(): Requires knowing the variable type ischar— not reliably greppable
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- .NET (Microsoft)
- Publisher
- .NET (Microsoft) (Official)
- Source
- dotnet/skills · plugins/dotnet-diag/skills/analyzing-dotnet-performance · commit 96c3d68
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by .NET (Microsoft) or .NET (Microsoft).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download analyzing-dotnet-performance.zip