@cratis/pi 7.102.0 → 7.103.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package/corpus/harnesses/copilot/instructions/profiles.instructions.md +10 -1
- package/package/corpus/harnesses/copilot/instructions/pull-requests.instructions.md +2 -0
- package/package/corpus/harnesses/copilot/instructions/secrets.instructions.md +4 -0
- package/package/corpus/hooks/README.md +11 -1
- package/package/corpus/hooks/scripts/cratis-check-pr.mjs +12 -1
- package/package/corpus/hooks/scripts/cratis-guard-secrets.sh +79 -23
- package/package/corpus/hooks/scripts/cratis-guard-writes.sh +145 -40
- package/package/corpus/rules/profiles.md +10 -1
- package/package/corpus/rules/pull-requests.md +2 -0
- package/package/corpus/rules/secrets.md +4 -0
- package/package/corpus/skills/analyzing-dotnet-performance/LICENSE +23 -0
- package/package/corpus/skills/analyzing-dotnet-performance/NOTICE +36 -0
- package/package/corpus/skills/analyzing-dotnet-performance/SKILL.md +214 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/async-patterns.md +122 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/collections-and-linq.md +220 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/critical-patterns.md +291 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/io-and-serialization.md +135 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/memory-and-strings.md +219 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/regex-patterns.md +95 -0
- package/package/corpus/skills/analyzing-dotnet-performance/references/structural-patterns.md +38 -0
- package/package/corpus/skills/binlog-generation/LICENSE +23 -0
- package/package/corpus/skills/binlog-generation/NOTICE +22 -0
- package/package/corpus/skills/binlog-generation/SKILL.md +129 -0
- package/package/corpus/skills/check-bin-obj-clash/LICENSE +23 -0
- package/package/corpus/skills/check-bin-obj-clash/NOTICE +27 -0
- package/package/corpus/skills/check-bin-obj-clash/SKILL.md +127 -0
- package/package/corpus/skills/check-bin-obj-clash/references/common-causes-and-fixes.md +206 -0
- package/package/corpus/skills/coverage-analysis/LICENSE +23 -0
- package/package/corpus/skills/coverage-analysis/NOTICE +32 -0
- package/package/corpus/skills/coverage-analysis/SKILL.md +198 -0
- package/package/corpus/skills/coverage-analysis/references/guidelines.md +68 -0
- package/package/corpus/skills/coverage-analysis/references/output-format.md +91 -0
- package/package/corpus/skills/coverage-analysis/references/report-generation.md +58 -0
- package/package/corpus/skills/coverage-analysis/references/setup-discovery.md +307 -0
- package/package/corpus/skills/coverage-analysis/scripts/Compute-CrapScores.ps1 +80 -0
- package/package/corpus/skills/coverage-analysis/scripts/CoverageData.ps1 +272 -0
- package/package/corpus/skills/coverage-analysis/scripts/Extract-MethodCoverage.ps1 +65 -0
- package/package/corpus/skills/csharp-refactoring/LICENSE +23 -0
- package/package/corpus/skills/csharp-refactoring/NOTICE +22 -0
- package/package/corpus/skills/csharp-refactoring/SKILL.md +175 -0
- package/package/corpus/skills/csharp-refactoring/references/operation-catalog.md +37 -0
- package/package/corpus/skills/directory-build-organization/LICENSE +23 -0
- package/package/corpus/skills/directory-build-organization/NOTICE +21 -0
- package/package/corpus/skills/directory-build-organization/SKILL.md +205 -0
- package/package/corpus/skills/directory-build-organization/references/common-patterns.md +56 -0
- package/package/corpus/skills/directory-build-organization/references/multi-level-examples.md +167 -0
- package/package/corpus/skills/directory-build-organization/references/targetframework-props-pitfall.md +54 -0
- package/package/corpus/skills/dotnet-aot-compat/LICENSE +23 -0
- package/package/corpus/skills/dotnet-aot-compat/NOTICE +18 -0
- package/package/corpus/skills/dotnet-aot-compat/SKILL.md +265 -0
- package/package/corpus/skills/dotnet-aot-compat/references/polyfills.md +43 -0
- package/package/corpus/skills/dotnet-trace-collect/LICENSE +23 -0
- package/package/corpus/skills/dotnet-trace-collect/NOTICE +65 -0
- package/package/corpus/skills/dotnet-trace-collect/SKILL.md +116 -0
- package/package/corpus/skills/dotnet-trace-collect/references/dotnet-monitor.md +97 -0
- package/package/corpus/skills/dotnet-trace-collect/references/dotnet-trace-collect-linux.md +84 -0
- package/package/corpus/skills/dotnet-trace-collect/references/dotnet-trace-collect.md +91 -0
- package/package/corpus/skills/dotnet-trace-collect/references/perfcollect.md +200 -0
- package/package/corpus/skills/dotnet-trace-collect/references/perfview.md +141 -0
- package/package/corpus/skills/dotnet-trace-collect/references/tool-selection.md +160 -0
- package/package/corpus/skills/dump-collect/LICENSE +23 -0
- package/package/corpus/skills/dump-collect/NOTICE +40 -0
- package/package/corpus/skills/dump-collect/SKILL.md +97 -0
- package/package/corpus/skills/dump-collect/references/container-dumps.md +412 -0
- package/package/corpus/skills/dump-collect/references/coreclr-dumps.md +108 -0
- package/package/corpus/skills/dump-collect/references/nativeaot-dumps.md +280 -0
- package/package/corpus/skills/eliminate-redundant-restores/LICENSE +23 -0
- package/package/corpus/skills/eliminate-redundant-restores/NOTICE +19 -0
- package/package/corpus/skills/eliminate-redundant-restores/SKILL.md +112 -0
- package/package/corpus/skills/extension-points/LICENSE +23 -0
- package/package/corpus/skills/extension-points/NOTICE +18 -0
- package/package/corpus/skills/extension-points/SKILL.md +248 -0
- package/package/corpus/skills/filter-syntax/LICENSE +23 -0
- package/package/corpus/skills/filter-syntax/NOTICE +17 -0
- package/package/corpus/skills/filter-syntax/SKILL.md +179 -0
- package/package/corpus/skills/including-generated-files/LICENSE +23 -0
- package/package/corpus/skills/including-generated-files/NOTICE +17 -0
- package/package/corpus/skills/including-generated-files/SKILL.md +139 -0
- package/package/corpus/skills/microbenchmarking/LICENSE +23 -0
- package/package/corpus/skills/microbenchmarking/NOTICE +36 -0
- package/package/corpus/skills/microbenchmarking/SKILL.md +131 -0
- package/package/corpus/skills/microbenchmarking/references/bdn-internals-and-tuning.md +143 -0
- package/package/corpus/skills/microbenchmarking/references/comparison-strategies.md +200 -0
- package/package/corpus/skills/microbenchmarking/references/diagnosers-and-exporters.md +150 -0
- package/package/corpus/skills/microbenchmarking/references/project-setup-and-running.md +189 -0
- package/package/corpus/skills/microbenchmarking/references/writing-benchmarks.md +310 -0
- package/package/corpus/skills/msbuild/LICENSE +23 -0
- package/package/corpus/skills/msbuild/NOTICE +55 -0
- package/package/corpus/skills/msbuild/SKILL.md +117 -0
- package/package/corpus/skills/msbuild/references/antipatterns/additional-antipatterns.md +291 -0
- package/package/corpus/skills/msbuild/references/antipatterns/incremental-build-inputs-outputs.md +57 -0
- package/package/corpus/skills/msbuild/references/antipatterns/private-assets.md +29 -0
- package/package/corpus/skills/msbuild/references/binlog-failure-analysis.md +85 -0
- package/package/corpus/skills/msbuild/references/binlog-generation.md +69 -0
- package/package/corpus/skills/msbuild/references/build-perf-baseline.md +493 -0
- package/package/corpus/skills/msbuild/references/build-perf-diagnostics.md +268 -0
- package/package/corpus/skills/msbuild/references/copy-to-output-directory.md +183 -0
- package/package/corpus/skills/msbuild/references/eval-performance.md +190 -0
- package/package/corpus/skills/msbuild/references/extension-points.md +281 -0
- package/package/corpus/skills/msbuild/references/incremental-build.md +365 -0
- package/package/corpus/skills/msbuild/references/msbuild-antipatterns.md +401 -0
- package/package/corpus/skills/orleans/LICENSE +21 -0
- package/package/corpus/skills/orleans/NOTICE +64 -0
- package/package/corpus/skills/orleans/SKILL.md +140 -0
- package/package/corpus/skills/orleans/references/anti-patterns.md +660 -0
- package/package/corpus/skills/orleans/references/configuration-api.md +933 -0
- package/package/corpus/skills/orleans/references/examples.md +66 -0
- package/package/corpus/skills/orleans/references/grain-api.md +784 -0
- package/package/corpus/skills/orleans/references/grains.md +75 -0
- package/package/corpus/skills/orleans/references/hosting.md +71 -0
- package/package/corpus/skills/orleans/references/implementation.md +591 -0
- package/package/corpus/skills/orleans/references/official-docs-index.md +250 -0
- package/package/corpus/skills/orleans/references/patterns.md +811 -0
- package/package/corpus/skills/orleans/references/persistence-api.md +495 -0
- package/package/corpus/skills/orleans/references/primitive-selection.md +35 -0
- package/package/corpus/skills/orleans/references/scheduling-and-services.md +295 -0
- package/package/corpus/skills/orleans/references/serialization-api.md +299 -0
- package/package/corpus/skills/orleans/references/streaming-api.md +396 -0
- package/package/corpus/skills/orleans/references/testing-patterns.md +210 -0
- package/package/corpus/skills/platform-detection/LICENSE +23 -0
- package/package/corpus/skills/platform-detection/NOTICE +17 -0
- package/package/corpus/skills/platform-detection/SKILL.md +230 -0
- package/package/corpus/skills/platform-detection/references/command-mode.md +27 -0
- package/package/corpus/skills/profiling/LICENSE +21 -0
- package/package/corpus/skills/profiling/NOTICE +50 -0
- package/package/corpus/skills/profiling/SKILL.md +144 -0
- package/package/corpus/skills/profiling/references/commands.md +439 -0
- package/package/corpus/skills/profiling/references/patterns.md +586 -0
- package/package/corpus/skills/profiling/references/profiling.md +190 -0
- package/package/corpus/skills/run-tests/LICENSE +23 -0
- package/package/corpus/skills/run-tests/NOTICE +19 -0
- package/package/corpus/skills/run-tests/SKILL.md +305 -0
- package/package/corpus/skills/target-authoring/LICENSE +23 -0
- package/package/corpus/skills/target-authoring/NOTICE +17 -0
- package/package/corpus/skills/target-authoring/SKILL.md +165 -0
- package/package/corpus/skills/vectorization/LICENSE +23 -0
- package/package/corpus/skills/vectorization/NOTICE +17 -0
- package/package/corpus/skills/vectorization/SKILL.md +189 -0
- package/package/profile-catalog.json +85 -1
- package/package.json +1 -1
|
@@ -86,11 +86,20 @@ profile includes neither Screenplay nor Stage.
|
|
|
86
86
|
| Profile ID | Description | Automatically Includes |
|
|
87
87
|
|---|---|---|
|
|
88
88
|
| `cratis/engineering` | Engineering conventions and workflows | `cratis/engineering/core`, `cratis/engineering/csharp`, `cratis/engineering/elixir`, `cratis/engineering/go`, `cratis/engineering/kotlin`, `cratis/engineering/react`, `cratis/engineering/typescript` |
|
|
89
|
-
| `cratis/engineering/csharp` | C# engineering conventions and framework Orleans jobs (`cratis-orleans-jobs`, alongside `orleans.md`) | `cratis/engineering/core` |
|
|
89
|
+
| `cratis/engineering/csharp` | C# engineering conventions, .NET engineering skills, and framework Orleans jobs (`cratis-orleans-jobs`, alongside `orleans.md`) | `cratis/engineering/core`, `cratis/engineering/dotnet` |
|
|
90
|
+
| `cratis/engineering/dotnet` | Upstream .NET engineering workflows | `cratis/engineering/dotnet/performance`, `cratis/engineering/dotnet/diagnostics`, `cratis/engineering/dotnet/msbuild`, `cratis/engineering/dotnet/orleans`, `cratis/engineering/dotnet/testing`, `cratis/engineering/dotnet/refactoring` |
|
|
91
|
+
| `cratis/engineering/dotnet/performance` | Microbenchmarking, performance patterns, SIMD, and profiling | (no child profiles) |
|
|
92
|
+
| `cratis/engineering/dotnet/diagnostics` | Trace and crash-dump collection | (no child profiles) |
|
|
93
|
+
| `cratis/engineering/dotnet/msbuild` | MSBuild troubleshooting, build authoring, output paths, and binlogs | (no child profiles) |
|
|
94
|
+
| `cratis/engineering/dotnet/orleans` | Orleans primitives, hosting, persistence, and runtime behavior | (no child profiles) |
|
|
95
|
+
| `cratis/engineering/dotnet/testing` | Test-platform detection, runner commands, filters, and coverage | (no child profiles) |
|
|
96
|
+
| `cratis/engineering/dotnet/refactoring` | Behavior-preserving C# refactoring and AOT compatibility | (no child profiles) |
|
|
90
97
|
| `cratis/engineering/go` | Go framework parity and immutable module releases | `cratis/engineering/core`, `cratis/language/go` |
|
|
91
98
|
| `cratis/engineering/typescript` | TypeScript engineering conventions | `cratis/engineering/core` |
|
|
92
99
|
| `cratis/engineering/react` | React engineering conventions | `cratis/engineering/core` |
|
|
93
100
|
|
|
101
|
+
The `cratis/engineering/dotnet` profiles carry upstream skills under MIT, with attribution and changes in each skill's NOTICE. Cratis rules and the `cratis-*` skills win where they differ.
|
|
102
|
+
|
|
94
103
|
The `cratis/engineering` profile also carries [issue-assignment.md](./issue-assignment.md): when an agent starts work on a numbered issue in a known repository and nobody is assigned, it assigns the current `gh` user.
|
|
95
104
|
|
|
96
105
|
### Language Profiles
|
|
@@ -8,6 +8,8 @@ applyTo: "**/*"
|
|
|
8
8
|
|
|
9
9
|
**The PR description is published verbatim as the GitHub release. In repositories released by `cratis/release-action`, it also closes every issue written as `(#n)`; elsewhere, follow the repository's own release and issue-closing process.** Write the note the person upgrading should read, not a development write-up. The same contract applies to release notes typed into a manual workflow run or written straight into a release. Where it is installed, the `policy / verify` check enforces it on release-bound PRs into the default branch carrying `major`/`minor`/`patch` (it re-runs when the label is added); its release-note step warns on `no-release` and unlabelled PRs, which must still be written this way because any of them may become releasable. `release-action` does not run for a `no-release` PR, so `(#n)` closes nothing there. Editing the description re-runs the check. HTML comments are not shown on the release page and the check ignores them for headings, keywords and placeholders, and `release-action` removes them before publishing, so a `(#n)` only inside a comment closes nothing; the check fails it, so never put an issue reference in a comment. The template's own comment can stay: its `(#123)` examples are inline code, and the comment is not published.
|
|
10
10
|
|
|
11
|
+
**A change to a hook script or its wiring (`.cratis/ai/hooks/**`) needs a release-note line that tells consumers to run `cratis ai update`; a hook fix does not reach a repository until they do.**
|
|
12
|
+
|
|
11
13
|
### Allowed shape
|
|
12
14
|
|
|
13
15
|
- Follow the repository's pull request template (`.github/pull_request_template.md`) within this contract.
|
|
@@ -20,6 +20,10 @@ Every line is tagged **[contract]** (binding) per the Three Levels of Authority
|
|
|
20
20
|
- **[contract] Project the field you need and say which one:** `-o jsonpath='{.spec.containers[*].image}'`,
|
|
21
21
|
`-o custom-columns=…`, `kubectl get … -o name`, status fields, `kubectl logs`, `docker inspect --format`.
|
|
22
22
|
Read a `.env.example`, never the `.env`.
|
|
23
|
+
- **[contract] The hook reads command text only.** It cannot see a command piped into a shell
|
|
24
|
+
(`… | sh`, `bash -c "$(…)"`), a recursive search with no named file (`grep -r PASSWORD .`), or a
|
|
25
|
+
value reached through a variable, alias or script. These stay your rule to keep; output redaction
|
|
26
|
+
is the only backstop.
|
|
23
27
|
|
|
24
28
|
## Values
|
|
25
29
|
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) .NET Foundation and Contributors
|
|
4
|
+
|
|
5
|
+
All rights reserved.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
.NET Performance Patterns
|
|
2
|
+
Copyright (c) .NET Foundation and Contributors
|
|
3
|
+
Licensed under the MIT License. See LICENSE.
|
|
4
|
+
|
|
5
|
+
Upstream source: https://github.com/dotnet/skills/blob/a6bf43ab61967c30919334986515163ab24d7635/plugins/dotnet-diag/skills/analyzing-dotnet-performance/SKILL.md
|
|
6
|
+
|
|
7
|
+
Changes made by Cratis:
|
|
8
|
+
|
|
9
|
+
LICENSE:
|
|
10
|
+
- Copy upstream MIT license and copyright verbatim.
|
|
11
|
+
|
|
12
|
+
SKILL.md:
|
|
13
|
+
- Replace "I/O" with "input/output" in the description to satisfy the neutral-voice rule.
|
|
14
|
+
- Normalize frontmatter serialization, add MIT license where absent; preserve name and description.
|
|
15
|
+
- Add marked modification/source comment and applicability/Cratis precedence line.
|
|
16
|
+
- Rewrite the description to the Cratis shape (what it does, Use when, Not for) and drop references to skills that are not part of this corpus.
|
|
17
|
+
|
|
18
|
+
references/structural-patterns.md:
|
|
19
|
+
- Qualify sealing advice to preserve published framework/library public API compatibility.
|
|
20
|
+
|
|
21
|
+
references/async-patterns.md:
|
|
22
|
+
- Add or normalize the top Contents list from existing headings; preserve section content.
|
|
23
|
+
|
|
24
|
+
references/collections-and-linq.md:
|
|
25
|
+
- Add or normalize the top Contents list from existing headings; preserve section content.
|
|
26
|
+
|
|
27
|
+
references/critical-patterns.md:
|
|
28
|
+
- Add or normalize the top Contents list from existing headings; preserve section content.
|
|
29
|
+
|
|
30
|
+
references/io-and-serialization.md:
|
|
31
|
+
- Add or normalize the top Contents list from existing headings; preserve section content.
|
|
32
|
+
|
|
33
|
+
references/memory-and-strings.md:
|
|
34
|
+
- Add or normalize the top Contents list from existing headings; preserve section content.
|
|
35
|
+
|
|
36
|
+
NOTICE: Add this attribution, change list, and any download/execution disclosure.
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: analyzing-dotnet-performance
|
|
3
|
+
description: 'Scans .NET code for about 50 performance anti-patterns across async, memory, strings, collections, LINQ, regex, serialization, and input/output, with tiered severity. Use when analyzing .NET code for optimization opportunities, reviewing hot paths, or auditing allocation-heavy patterns. Not for measuring or profiling a running process (use profiling or microbenchmarking) or for SIMD work (use vectorization).'
|
|
4
|
+
license: MIT
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
<!-- Modified by Cratis from dotnet's original (MIT): frontmatter, applicability, navigation and the changes listed in NOTICE. Upstream: https://github.com/dotnet/skills (plugins/dotnet-diag/skills/analyzing-dotnet-performance/SKILL.md; see NOTICE) -->
|
|
8
|
+
|
|
9
|
+
# .NET Performance Patterns
|
|
10
|
+
|
|
11
|
+
Cratis rules in `.cratis/ai/rules/` (including `csharp.md`, `specs.csharp.md`, and `orleans.md`) and the `cratis-*` skills win where they differ.
|
|
12
|
+
|
|
13
|
+
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.
|
|
14
|
+
|
|
15
|
+
## When to Use
|
|
16
|
+
|
|
17
|
+
- Reviewing C#/.NET code for performance optimization opportunities
|
|
18
|
+
- Auditing hot paths for allocation-heavy or inefficient patterns
|
|
19
|
+
- Systematic scan of a codebase for known anti-patterns before release
|
|
20
|
+
- Second-opinion analysis after manual performance review
|
|
21
|
+
|
|
22
|
+
## When Not to Use
|
|
23
|
+
|
|
24
|
+
- **Algorithmic complexity analysis** — this skill targets API usage patterns, not algorithm design
|
|
25
|
+
- **Code not on a hot path** with no performance requirements — avoid premature optimization
|
|
26
|
+
|
|
27
|
+
## Inputs
|
|
28
|
+
|
|
29
|
+
| Input | Required | Description |
|
|
30
|
+
|-------|----------|-------------|
|
|
31
|
+
| Source code | Yes | C# files, code blocks, or repository paths to scan |
|
|
32
|
+
| Hot-path context | Recommended | Which code paths are performance-critical |
|
|
33
|
+
| Target framework | Recommended | .NET version (some patterns require .NET 8+) |
|
|
34
|
+
| Scan depth | Optional | `critical-only`, `standard` (default), or `comprehensive` |
|
|
35
|
+
|
|
36
|
+
## Workflow
|
|
37
|
+
|
|
38
|
+
### Step 1: Load Critical Reference
|
|
39
|
+
|
|
40
|
+
Resolve bundled paths from the directory that contains this `SKILL.md`, not from the user's workspace. Load this reference file first:
|
|
41
|
+
|
|
42
|
+
- `references/critical-patterns.md`
|
|
43
|
+
|
|
44
|
+
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.
|
|
45
|
+
|
|
46
|
+
### Step 2: Detect Code Signals and Select Topic Recipes
|
|
47
|
+
|
|
48
|
+
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.
|
|
49
|
+
|
|
50
|
+
After detecting signals, load only the topic-specific references selected by scan depth:
|
|
51
|
+
|
|
52
|
+
- `critical-only`: No additional references (use only `critical-patterns.md`)
|
|
53
|
+
- `standard` (default): Load references matching detected signals from this list:
|
|
54
|
+
- `references/async-patterns.md` — async/Task/ValueTask signals
|
|
55
|
+
- `references/memory-and-strings.md` — Span/Memory/string allocation signals
|
|
56
|
+
- `references/regex-patterns.md` — Regex signals
|
|
57
|
+
- `references/collections-and-linq.md` — Dictionary/List/LINQ signals
|
|
58
|
+
- `references/io-and-serialization.md` — JsonSerializer/HttpClient/Stream signals
|
|
59
|
+
- `references/structural-patterns.md` — always loaded (unsealed classes checked regardless)
|
|
60
|
+
- `comprehensive`: Load all six topic-specific references above
|
|
61
|
+
|
|
62
|
+
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.
|
|
63
|
+
|
|
64
|
+
Use the `## Detection` sections from loaded reference files and the inline recipes in Step 3 for categories whose reference files are unavailable.
|
|
65
|
+
|
|
66
|
+
| Signal in Code | Topic |
|
|
67
|
+
|----------------|-------|
|
|
68
|
+
| `async`, `await`, `Task`, `ValueTask` | Async patterns |
|
|
69
|
+
| `Span<`, `Memory<`, `stackalloc`, `ArrayPool`, `string.Substring`, `.Replace(`, `.ToLower()`, `+=` in loops, `params` | Memory & strings |
|
|
70
|
+
| `Regex`, `[GeneratedRegex]`, `Regex.Match`, `RegexOptions.Compiled` | Regex patterns |
|
|
71
|
+
| `Dictionary<`, `List<`, `.ToList()`, `.Where(`, `.Select(`, LINQ methods, `static readonly Dictionary<` | Collections & LINQ |
|
|
72
|
+
| `JsonSerializer`, `HttpClient`, `Stream`, `FileStream` | I/O & serialization |
|
|
73
|
+
|
|
74
|
+
Always check structural patterns (unsealed classes) regardless of signals.
|
|
75
|
+
|
|
76
|
+
**Scan depth controls scope:**
|
|
77
|
+
- `critical-only`: Only critical patterns (deadlocks, >10x regressions)
|
|
78
|
+
- `standard` (default): Critical + detected topic patterns
|
|
79
|
+
- `comprehensive`: All pattern categories
|
|
80
|
+
|
|
81
|
+
### Step 3: Scan and Report
|
|
82
|
+
|
|
83
|
+
**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.
|
|
84
|
+
|
|
85
|
+
For each relevant pattern category, run the detection recipes below. Report exact counts, not estimates.
|
|
86
|
+
|
|
87
|
+
**Core scan recipes** (run these when reference files aren't available):
|
|
88
|
+
```
|
|
89
|
+
# Strings & memory
|
|
90
|
+
grep -n '\.IndexOf(\"' FILE # Missing StringComparison
|
|
91
|
+
grep -n '\.Substring(' FILE # Substring allocations
|
|
92
|
+
grep -En '\.(StartsWith|EndsWith|Contains)\s*\(' FILE # Missing StringComparison
|
|
93
|
+
grep -n '\.ToLower()\|\.ToUpper()' FILE # Culture-sensitive + allocation
|
|
94
|
+
grep -n '\.Replace(' FILE # Chained Replace allocations
|
|
95
|
+
grep -n 'params ' FILE # params array allocation
|
|
96
|
+
|
|
97
|
+
# Collections & LINQ
|
|
98
|
+
grep -n '\.Select\|\.Where\|\.OrderBy\|\.GroupBy' FILE # LINQ on hot path
|
|
99
|
+
grep -n '\.All\|\.Any' FILE # LINQ on string/char
|
|
100
|
+
grep -n 'new Dictionary<\|new List<' FILE # Per-call allocation
|
|
101
|
+
grep -n 'static readonly Dictionary<' FILE # FrozenDictionary candidate
|
|
102
|
+
|
|
103
|
+
# Regex
|
|
104
|
+
grep -n 'RegexOptions.Compiled' FILE # Compiled regex budget
|
|
105
|
+
grep -n 'new Regex(' FILE # Per-call regex
|
|
106
|
+
grep -n 'GeneratedRegex' FILE # Positive: source-gen regex
|
|
107
|
+
|
|
108
|
+
# Structural
|
|
109
|
+
grep -n 'public class \|internal class ' FILE # Unsealed classes
|
|
110
|
+
grep -n 'sealed class' FILE # Already sealed
|
|
111
|
+
grep -n ': IEquatable' FILE # Positive: struct equality
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**Rules:**
|
|
115
|
+
- Run every relevant recipe for the detected pattern categories
|
|
116
|
+
- **Emit a scan execution checklist** before classifying findings — list each recipe and the hit count
|
|
117
|
+
- A result of **0 hits** is valid and valuable (confirms good practice)
|
|
118
|
+
- If reference files were loaded, also run their `## Detection` recipes
|
|
119
|
+
|
|
120
|
+
**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.
|
|
121
|
+
|
|
122
|
+
### Step 3b: Cross-File Consistency Check
|
|
123
|
+
|
|
124
|
+
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.
|
|
125
|
+
|
|
126
|
+
### Step 3c: Compound Allocation Check
|
|
127
|
+
|
|
128
|
+
After running scan recipes, look for these multi-allocation patterns that single-line recipes miss:
|
|
129
|
+
|
|
130
|
+
1. **Branched `.Replace()` chains:** Methods that call `.Replace()` across multiple `if/else` branches — report total allocation count across all branches, not just per-line.
|
|
131
|
+
2. **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.
|
|
132
|
+
3. **Compound `+=` with embedded allocating calls:** Lines like `result += $"...{Foo().ToLower()}"` are 2+ allocations (interpolation + ToLower + concatenation) — flag the compound cost, not just the `.ToLower()`.
|
|
133
|
+
4. **`string.Format` specificity:** Distinguish resource-loaded format strings (not fixable) from compile-time literal format strings (fixable with interpolation). Enumerate the actionable sites.
|
|
134
|
+
|
|
135
|
+
### Step 4: Classify and Prioritize Findings
|
|
136
|
+
|
|
137
|
+
Assign each finding a severity:
|
|
138
|
+
|
|
139
|
+
| Severity | Criteria | Action |
|
|
140
|
+
|----------|----------|--------|
|
|
141
|
+
| 🔴 **Critical** | Deadlocks, crashes, security vulnerabilities, >10x regression | Must fix |
|
|
142
|
+
| 🟡 **Moderate** | 2-10x improvement opportunity, best practice for hot paths | Should fix on hot paths |
|
|
143
|
+
| ℹ️ **Info** | Pattern applies but code may not be on a hot path | Consider if profiling shows impact |
|
|
144
|
+
|
|
145
|
+
**Prioritization rules:**
|
|
146
|
+
1. If the user identified hot-path code, elevate all findings in that code to their maximum severity
|
|
147
|
+
2. 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"_
|
|
148
|
+
3. Never suggest micro-optimizations on code that is clearly not performance-sensitive
|
|
149
|
+
|
|
150
|
+
**Scale-based severity escalation:**
|
|
151
|
+
When the same pattern appears across many instances, escalate severity:
|
|
152
|
+
- 1-10 instances of the same anti-pattern → report at the pattern's base severity
|
|
153
|
+
- 11-50 instances → escalate ℹ️ Info patterns to 🟡 Moderate
|
|
154
|
+
- 50+ instances → escalate to 🟡 Moderate with elevated priority; flag as a codebase-wide systematic issue
|
|
155
|
+
|
|
156
|
+
Always report exact counts (from scan recipes), not estimates or agent summaries.
|
|
157
|
+
|
|
158
|
+
### Step 5: Generate Findings
|
|
159
|
+
|
|
160
|
+
**Keep findings compact.** Each finding is one short block — not an essay. Group by severity (🔴 → 🟡 → ℹ️), not by file.
|
|
161
|
+
|
|
162
|
+
Format per finding:
|
|
163
|
+
|
|
164
|
+
```
|
|
165
|
+
#### ID. Title (N instances)
|
|
166
|
+
**Impact:** one-line impact statement
|
|
167
|
+
**Files:** file1.cs:L1, file2.cs:L2, ... (list locations, don't build tables)
|
|
168
|
+
**Fix:** one-line description of the change (e.g., "Add `StringComparison.Ordinal` parameter")
|
|
169
|
+
**Caveat:** only if non-obvious (version requirement, correctness risk)
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
**Rules for compact output:**
|
|
173
|
+
- **No ❌/✅ code blocks** for trivial fixes (adding a keyword, parameter, or type change). A one-line fix description suffices.
|
|
174
|
+
- **Only include code blocks** for non-obvious transformations (e.g., replacing a LINQ chain with a foreach loop, or hoisting a closure).
|
|
175
|
+
- **File locations as inline comma-separated list**, not a table. Use `File.cs:L42` format.
|
|
176
|
+
- **No explanatory prose** beyond the Impact line — the severity icon already conveys urgency.
|
|
177
|
+
- **Merge related findings** that share the same fix (e.g., all `.ToLower()` calls go in one finding, not split by file).
|
|
178
|
+
- **Positive findings** in a bullet list, not a table. One line per pattern: `✅ Pattern — evidence`.
|
|
179
|
+
|
|
180
|
+
End with a summary table and disclaimer:
|
|
181
|
+
|
|
182
|
+
```markdown
|
|
183
|
+
| Severity | Count | Top Issue |
|
|
184
|
+
|----------|-------|-----------|
|
|
185
|
+
| 🔴 Critical | N | ... |
|
|
186
|
+
| 🟡 Moderate | N | ... |
|
|
187
|
+
| ℹ️ Info | N | ... |
|
|
188
|
+
|
|
189
|
+
> ⚠️ **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.
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Validation
|
|
193
|
+
|
|
194
|
+
Before delivering results, verify:
|
|
195
|
+
|
|
196
|
+
- [ ] All critical patterns were checked (from reference files or inline recipes)
|
|
197
|
+
- [ ] Topic-specific recipes run only when matching signals detected
|
|
198
|
+
- [ ] Each finding includes a concrete code fix
|
|
199
|
+
- [ ] Scan execution checklist is complete (all recipes run)
|
|
200
|
+
- [ ] Summary table included at end
|
|
201
|
+
|
|
202
|
+
## Common Pitfalls
|
|
203
|
+
|
|
204
|
+
| Pitfall | Correct Approach |
|
|
205
|
+
|---------|-----------------|
|
|
206
|
+
| Flagging every `Dictionary` as needing `FrozenDictionary` | Only flag if the dictionary is never mutated after construction |
|
|
207
|
+
| Suggesting `Span<T>` in async methods | Use `Memory<T>` in async code; `Span<T>` only in sync hot paths |
|
|
208
|
+
| 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 |
|
|
209
|
+
| Suggesting `ConfigureAwait(false)` in app code | Only applicable in library code; not primarily a performance concern |
|
|
210
|
+
| Recommending `ValueTask` everywhere | Only for hot paths with frequent synchronous completion |
|
|
211
|
+
| Flagging `new HttpClient()` in DI services | Check if `IHttpClientFactory` is already in use |
|
|
212
|
+
| Suggesting `[GeneratedRegex]` for dynamic patterns | Only flag when the pattern string is a compile-time literal |
|
|
213
|
+
| Suggesting `CollectionsMarshal.AsSpan` broadly | Only for ultra-hot paths with benchmarked evidence; adds complexity and fragility |
|
|
214
|
+
| 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 |
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Async & Concurrency Patterns
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Don't Expose Async Wrappers for Sync Methods
|
|
6
|
+
- Don't Expose Sync Wrappers for Async Methods
|
|
7
|
+
- Use ValueTask for Hot Paths with Frequent Sync Completion
|
|
8
|
+
- Use Channels for Producer/Consumer
|
|
9
|
+
- Avoid False Sharing with Thread-Local State
|
|
10
|
+
- Detection
|
|
11
|
+
- Patterns Requiring Manual Review
|
|
12
|
+
|
|
13
|
+
### Don't Expose Async Wrappers for Sync Methods
|
|
14
|
+
🟡 **AVOID** wrapping sync methods with `Task.Run` in libraries | .NET Core+
|
|
15
|
+
|
|
16
|
+
❌
|
|
17
|
+
```csharp
|
|
18
|
+
public Task<int> ComputeHashAsync(byte[] data) =>
|
|
19
|
+
Task.Run(() => ComputeHash(data));
|
|
20
|
+
```
|
|
21
|
+
✅
|
|
22
|
+
```csharp
|
|
23
|
+
public int ComputeHash(byte[] data) { /* CPU-bound work */ }
|
|
24
|
+
// Consumer decides: var hash = await Task.Run(() => lib.ComputeHash(data));
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
**Impact: Eliminates unnecessary thread pool queue/dequeue overhead per call.**
|
|
28
|
+
|
|
29
|
+
### Don't Expose Sync Wrappers for Async Methods
|
|
30
|
+
🟡 **AVOID** creating sync wrappers that block on async implementations | .NET Core+
|
|
31
|
+
|
|
32
|
+
❌
|
|
33
|
+
```csharp
|
|
34
|
+
public string GetData() => GetDataAsync().Result;
|
|
35
|
+
```
|
|
36
|
+
✅
|
|
37
|
+
```csharp
|
|
38
|
+
public async Task<string> GetDataAsync() { /* ... */ }
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
**Impact: Prevents deadlocks and thread pool starvation from hidden sync-over-async blocking.**
|
|
42
|
+
|
|
43
|
+
### Use ValueTask for Hot Paths with Frequent Sync Completion
|
|
44
|
+
🟡 **DO** use `ValueTask<T>` on hot paths where sync completion is common | .NET Core 2.1+
|
|
45
|
+
|
|
46
|
+
❌
|
|
47
|
+
```csharp
|
|
48
|
+
public async Task<int> ReadAsync(Memory<byte> buffer)
|
|
49
|
+
{
|
|
50
|
+
if (_bufferedCount > 0)
|
|
51
|
+
return ReadFromBuffer(buffer.Span);
|
|
52
|
+
return await ReadAsyncCore(buffer);
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
✅
|
|
56
|
+
```csharp
|
|
57
|
+
public ValueTask<int> ReadAsync(Memory<byte> buffer)
|
|
58
|
+
{
|
|
59
|
+
if (_bufferedCount > 0)
|
|
60
|
+
return new ValueTask<int>(ReadFromBuffer(buffer.Span));
|
|
61
|
+
return new ValueTask<int>(ReadAsyncCore(buffer));
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
**Impact: Eliminates Task\<T\> allocation on synchronous completion — the struct stores results inline.**
|
|
66
|
+
|
|
67
|
+
### Use Channels for Producer/Consumer
|
|
68
|
+
🟡 **DO** use `System.Threading.Channels` for producer-consumer patterns | .NET Core 3.0+
|
|
69
|
+
|
|
70
|
+
❌
|
|
71
|
+
```csharp
|
|
72
|
+
var queue = new BlockingCollection<WorkItem>();
|
|
73
|
+
var item = queue.Take();
|
|
74
|
+
```
|
|
75
|
+
✅
|
|
76
|
+
```csharp
|
|
77
|
+
var channel = Channel.CreateUnbounded<WorkItem>();
|
|
78
|
+
|
|
79
|
+
// Producer
|
|
80
|
+
await channel.Writer.WriteAsync(item);
|
|
81
|
+
|
|
82
|
+
// Consumer
|
|
83
|
+
await foreach (var item in channel.Reader.ReadAllAsync())
|
|
84
|
+
Process(item);
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**Impact: ~25% faster, ~95% fewer GC collections vs manual approaches.**
|
|
88
|
+
|
|
89
|
+
### Avoid False Sharing with Thread-Local State
|
|
90
|
+
🟡 **AVOID** adjacent mutable fields written by different threads | .NET 7+
|
|
91
|
+
|
|
92
|
+
❌
|
|
93
|
+
```csharp
|
|
94
|
+
class SharedCounters
|
|
95
|
+
{
|
|
96
|
+
public long Counter1;
|
|
97
|
+
public long Counter2;
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
✅
|
|
101
|
+
```csharp
|
|
102
|
+
[StructLayout(LayoutKind.Explicit, Size = 128)]
|
|
103
|
+
struct PaddedCounter
|
|
104
|
+
{
|
|
105
|
+
[FieldOffset(0)] public long Value;
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
**Impact: Eliminates cross-core cache invalidation — can improve multi-threaded throughput by 10x+.**
|
|
110
|
+
|
|
111
|
+
## Detection
|
|
112
|
+
|
|
113
|
+
Scan recipes for async anti-patterns. Run these and report exact counts.
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
# async void methods (correctness issue — crashes on exception)
|
|
117
|
+
grep -rn --include='*.cs' 'async void' --exclude-dir=bin --exclude-dir=obj . | grep -v 'event' | wc -l
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Patterns Requiring Manual Review
|
|
121
|
+
|
|
122
|
+
- **Sync-over-async** (`.Result`, `.Wait()`): `.Result` matches any property named Result — needs type context to confirm it's `Task.Result`
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# Collections & LINQ Patterns
|
|
2
|
+
|
|
3
|
+
## Contents
|
|
4
|
+
|
|
5
|
+
- Use FrozenDictionary/FrozenSet for Read-Heavy Lookup Tables
|
|
6
|
+
- Use Dictionary Alternate Lookup for Span-Based Keys
|
|
7
|
+
- Use CollectionsMarshal.GetValueRefOrNullRef for Lookup-and-Update
|
|
8
|
+
- Use Collection Expressions [] for Zero-Allocation Span Creation
|
|
9
|
+
- Use EnsureCapacity on List/Stack/Queue Before Bulk Adds
|
|
10
|
+
- Use TryGetNonEnumeratedCount for Pre-Sizing
|
|
11
|
+
- Hoist Static Data Out of Method Bodies
|
|
12
|
+
- Add Overloads to Avoid params Array Allocation
|
|
13
|
+
- Detection
|
|
14
|
+
- Patterns Requiring Manual Review
|
|
15
|
+
|
|
16
|
+
### Use FrozenDictionary/FrozenSet for Read-Heavy Lookup Tables
|
|
17
|
+
🟡 **DO** use `FrozenDictionary`/`FrozenSet` for collections created once and read many times | .NET 8+
|
|
18
|
+
|
|
19
|
+
❌
|
|
20
|
+
```csharp
|
|
21
|
+
private static readonly Dictionary<string, int> s_statusCodes = new()
|
|
22
|
+
{
|
|
23
|
+
["OK"] = 200, ["NotFound"] = 404, ["InternalServerError"] = 500
|
|
24
|
+
};
|
|
25
|
+
```
|
|
26
|
+
✅
|
|
27
|
+
```csharp
|
|
28
|
+
private static readonly FrozenDictionary<string, int> s_statusCodes =
|
|
29
|
+
new Dictionary<string, int>
|
|
30
|
+
{
|
|
31
|
+
["OK"] = 200, ["NotFound"] = 404, ["InternalServerError"] = 500
|
|
32
|
+
}.ToFrozenDictionary();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**Impact: ~50% faster lookups than Dictionary, ~14x faster than ImmutableDictionary.**
|
|
36
|
+
|
|
37
|
+
### Use Dictionary Alternate Lookup for Span-Based Keys
|
|
38
|
+
🟡 **DO** use `GetAlternateLookup<ReadOnlySpan<char>>()` to avoid string allocation on lookups | .NET 9+
|
|
39
|
+
|
|
40
|
+
❌
|
|
41
|
+
```csharp
|
|
42
|
+
string key = headerLine.Substring(0, colonIndex);
|
|
43
|
+
if (s_dict.TryGetValue(key, out int value)) { /* ... */ }
|
|
44
|
+
```
|
|
45
|
+
✅
|
|
46
|
+
```csharp
|
|
47
|
+
var lookup = s_dict.GetAlternateLookup<ReadOnlySpan<char>>();
|
|
48
|
+
ReadOnlySpan<char> key = headerLine.AsSpan(0, colonIndex);
|
|
49
|
+
if (lookup.TryGetValue(key, out int value)) { }
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
**Impact: Avoids string allocation per lookup — especially valuable in parser/protocol hot paths.**
|
|
53
|
+
|
|
54
|
+
### Use CollectionsMarshal.GetValueRefOrNullRef for Lookup-and-Update
|
|
55
|
+
🟡 **DO** use `CollectionsMarshal.GetValueRefOrAddDefault` for dictionary update patterns | .NET 6+
|
|
56
|
+
|
|
57
|
+
❌
|
|
58
|
+
```csharp
|
|
59
|
+
_counts.TryGetValue(key, out int count);
|
|
60
|
+
_counts[key] = count + 1;
|
|
61
|
+
```
|
|
62
|
+
✅
|
|
63
|
+
```csharp
|
|
64
|
+
ref int count = ref CollectionsMarshal.GetValueRefOrAddDefault(_counts, key, out _);
|
|
65
|
+
count++;
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Impact: ~48% faster for lookup-and-update patterns (95µs → 49µs).**
|
|
69
|
+
|
|
70
|
+
### Use Collection Expressions [] for Zero-Allocation Span Creation
|
|
71
|
+
🟡 **DO** use collection expressions for `Span<T>` targets | C# 12 / .NET 8+
|
|
72
|
+
|
|
73
|
+
❌
|
|
74
|
+
```csharp
|
|
75
|
+
int[] values = new int[] { a, b, c, d };
|
|
76
|
+
```
|
|
77
|
+
✅
|
|
78
|
+
```csharp
|
|
79
|
+
Span<int> values = [a, b, c, d];
|
|
80
|
+
ReadOnlySpan<int> daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
**Impact: Zero heap allocation for span-targeted collection expressions.**
|
|
84
|
+
|
|
85
|
+
### Use EnsureCapacity on List/Stack/Queue Before Bulk Adds
|
|
86
|
+
🟡 **DO** call `EnsureCapacity` before bulk insertions | .NET 6+
|
|
87
|
+
|
|
88
|
+
❌
|
|
89
|
+
```csharp
|
|
90
|
+
var list = new List<int>();
|
|
91
|
+
for (int i = 0; i < 10000; i++)
|
|
92
|
+
list.Add(i);
|
|
93
|
+
```
|
|
94
|
+
✅
|
|
95
|
+
```csharp
|
|
96
|
+
var list = new List<int>();
|
|
97
|
+
list.EnsureCapacity(10000);
|
|
98
|
+
for (int i = 0; i < 10000; i++)
|
|
99
|
+
list.Add(i);
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
**Impact: Reduces reallocations and array copies during bulk operations.**
|
|
103
|
+
|
|
104
|
+
### Use TryGetNonEnumeratedCount for Pre-Sizing
|
|
105
|
+
🟡 **DO** use `TryGetNonEnumeratedCount` to pre-size destination collections | .NET 6+
|
|
106
|
+
|
|
107
|
+
❌
|
|
108
|
+
```csharp
|
|
109
|
+
var results = new List<int>();
|
|
110
|
+
foreach (var item in source)
|
|
111
|
+
results.Add(Transform(item));
|
|
112
|
+
```
|
|
113
|
+
✅
|
|
114
|
+
```csharp
|
|
115
|
+
var results = source.TryGetNonEnumeratedCount(out int count)
|
|
116
|
+
? new List<int>(count)
|
|
117
|
+
: new List<int>();
|
|
118
|
+
foreach (var item in source)
|
|
119
|
+
results.Add(Transform(item));
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
**Impact: Avoids O(n) enumeration for counting; eliminates resizing allocations.**
|
|
123
|
+
|
|
124
|
+
### Hoist Static Data Out of Method Bodies
|
|
125
|
+
🟡 **AVOID** creating collections with static/deterministic data inside method bodies | .NET Core+
|
|
126
|
+
|
|
127
|
+
❌
|
|
128
|
+
```csharp
|
|
129
|
+
public string Convert(long number)
|
|
130
|
+
{
|
|
131
|
+
var groupsMap = new Dictionary<long, Func<long, string>>
|
|
132
|
+
{
|
|
133
|
+
{ 1_000_000_000, n => $"{Convert(n)} billion" },
|
|
134
|
+
{ 1_000_000, n => $"{Convert(n)} million" },
|
|
135
|
+
{ 1_000, n => $"{Convert(n)} thousand" },
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
✅
|
|
140
|
+
```csharp
|
|
141
|
+
private static readonly FrozenDictionary<long, Func<long, string>> s_groupsMap =
|
|
142
|
+
new Dictionary<long, Func<long, string>>
|
|
143
|
+
{
|
|
144
|
+
{ 1_000_000_000, n => $"{Convert(n)} billion" },
|
|
145
|
+
{ 1_000_000, n => $"{Convert(n)} million" },
|
|
146
|
+
{ 1_000, n => $"{Convert(n)} thousand" },
|
|
147
|
+
}.ToFrozenDictionary();
|
|
148
|
+
|
|
149
|
+
public string Convert(long number)
|
|
150
|
+
{
|
|
151
|
+
// ... use s_groupsMap
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
**Impact: Eliminates collection + internal storage + closure allocations per call. For a Dictionary with N entries, saves ~N+3 allocations per invocation.**
|
|
156
|
+
|
|
157
|
+
### Add Overloads to Avoid params Array Allocation
|
|
158
|
+
🟡 **DO** add 1- and 2-argument overloads for methods that accept `params T[]`, or use `params ReadOnlySpan<T>` on .NET 9+ | .NET Core+
|
|
159
|
+
|
|
160
|
+
❌
|
|
161
|
+
```csharp
|
|
162
|
+
public static string Transform(this string input, params IStringTransformer[] transformers) =>
|
|
163
|
+
transformers.Aggregate(input, (current, t) => t.Transform(current));
|
|
164
|
+
|
|
165
|
+
"hello".Transform(To.TitleCase);
|
|
166
|
+
```
|
|
167
|
+
✅
|
|
168
|
+
```csharp
|
|
169
|
+
// Option A: Explicit overloads for common arities
|
|
170
|
+
public static string Transform(this string input, IStringTransformer transformer) =>
|
|
171
|
+
transformer.Transform(input);
|
|
172
|
+
|
|
173
|
+
public static string Transform(this string input, IStringTransformer t1, IStringTransformer t2) =>
|
|
174
|
+
t2.Transform(t1.Transform(input));
|
|
175
|
+
|
|
176
|
+
public static string Transform(this string input, params IStringTransformer[] transformers) =>
|
|
177
|
+
transformers.Aggregate(input, (current, t) => t.Transform(current));
|
|
178
|
+
|
|
179
|
+
// Option B (.NET 9+ / C# 13): params ReadOnlySpan<T> — zero heap allocation
|
|
180
|
+
public static string Transform(this string input, params ReadOnlySpan<IStringTransformer> transformers)
|
|
181
|
+
{
|
|
182
|
+
foreach (var t in transformers)
|
|
183
|
+
input = t.Transform(input);
|
|
184
|
+
return input;
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
**Impact: Eliminates one array allocation per call for the common 1- and 2-argument cases. `params ReadOnlySpan<T>` eliminates it for all arities.**
|
|
189
|
+
|
|
190
|
+
## Detection
|
|
191
|
+
|
|
192
|
+
Scan recipes for collection and LINQ anti-patterns. Run these and report exact counts.
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
# Static Dictionary not using FrozenDictionary (read-only after init)
|
|
196
|
+
grep -rn --include='*.cs' 'static readonly Dictionary<' --exclude-dir=bin --exclude-dir=obj . | wc -l
|
|
197
|
+
|
|
198
|
+
# Static FrozenDictionary (already optimized — verify the inverse)
|
|
199
|
+
grep -rn --include='*.cs' 'static readonly FrozenDictionary<' --exclude-dir=bin --exclude-dir=obj . | wc -l
|
|
200
|
+
|
|
201
|
+
# Per-call List allocation (inside method bodies, not static/readonly fields)
|
|
202
|
+
grep -rn --include='*.cs' 'new List<' --exclude-dir=bin --exclude-dir=obj . | grep -v 'static\|readonly' | wc -l
|
|
203
|
+
|
|
204
|
+
# Per-call Dictionary allocation (inside method bodies, not static/readonly fields)
|
|
205
|
+
grep -rn --include='*.cs' 'new Dictionary<' --exclude-dir=bin --exclude-dir=obj . | grep -v 'static\|readonly' | wc -l
|
|
206
|
+
|
|
207
|
+
# StringComparer.CurrentCulture usage (almost always wrong in library code — use Ordinal)
|
|
208
|
+
grep -rn --include='*.cs' 'StringComparer.CurrentCulture' --exclude-dir=bin --exclude-dir=obj . | wc -l
|
|
209
|
+
|
|
210
|
+
# LINQ chains in extension/hot-path files (.Select, .Where, .Cast, .Take, .Aggregate)
|
|
211
|
+
grep -rn --include='*.cs' -E '\.(Select|Where|Cast|Take|Aggregate)\(' --exclude-dir=bin --exclude-dir=obj . | wc -l
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
For the LINQ chain recipe: any hit in a file whose name ends in `Extensions.cs`, `Formatter.cs`, or implements a method called from a public extension method is a hot-path candidate. Inspect each hit in these files and flag LINQ chains that allocate delegates, enumerators, or intermediate collections on every call. Hits in localization converters or one-time initialization are lower priority.
|
|
215
|
+
|
|
216
|
+
### Patterns Requiring Manual Review
|
|
217
|
+
|
|
218
|
+
- **ContainsKey + indexer double-lookup**: Requires verifying the same key is used in a subsequent indexer access — multi-line/multi-statement context
|
|
219
|
+
- **LINQ on hot paths**: The LINQ chain recipe above catches call sites, but distinguishing hot-path from cold-path requires context. Prioritize hits in `*Extensions.cs` and `*Formatter.cs` files, which are typically called on every user invocation
|
|
220
|
+
- **`new Dictionary/List<` in method bodies vs fields**: The grep heuristic (`grep -v 'static\|readonly'`) catches most cases but may include false positives from field initializers without `static`/`readonly` — spot-check flagged lines
|