[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79WMCN0851FVWNJ3F3QWRAB":3,"skill-same:01M79WMCN0851FVWNJ3F3QWRAB":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79WMCN0851FVWNJ3F3QWRAB","blazing-fast-dotnet",null,"Tune a running .NET 10\u002F11 workload at the runtime level: profile with dotnet-counters, dotnet-trace, and Linux perf; inspect JIT codegen; set runtime, GC, and ThreadPool knobs; fix lock contention and false sharing; tune ASP.NET Core throughput and NativeAOT publish settings; plus quick high-performance C# tips. USE FOR: making a measured app, service, or benchmark workload faster when the cost sits in the runtime, GC, threading, or configuration, or when asked to profile it or read its JIT disassembly. DO NOT USE FOR: scanning code for performance anti-patterns (analyzing-dotnet-performance), designing or running BenchmarkDotNet benchmarks (microbenchmarking), or writing or reviewing SIMD code (vectorization).","Blind-Striker\u002Fagent-skills-and-plugins","Blind-Striker","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1965259?v=4","01M79WFXTE5PH0C1VB7B54ANMN","Deniz İrgin","01M79WFXV5KZ5GST1K8G035DM5",1,"MIT","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fcodex\u002Fdeniz-dotnet-general\u002Fskills\u002Fblazing-fast-dotnet\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fcodex\u002Fdeniz-dotnet-general\u002Fskills\u002Fblazing-fast-dotnet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: blazing-fast-dotnet\ndescription: \"Tune a running .NET 10\u002F11 workload at the runtime level: profile\n  with dotnet-counters, dotnet-trace, and Linux perf; inspect JIT codegen; set\n  runtime, GC, and ThreadPool knobs; fix lock contention and false sharing; tune\n  ASP.NET Core throughput and NativeAOT publish settings; plus quick\n  high-performance C# tips. USE FOR: making a measured app, service, or\n  benchmark workload faster when the cost sits in the runtime, GC, threading, or\n  configuration, or when asked to profile it or read its JIT disassembly. DO NOT\n  USE FOR: scanning code for performance anti-patterns\n  (analyzing-dotnet-performance), designing or running BenchmarkDotNet\n  benchmarks (microbenchmarking), or writing or reviewing SIMD code\n  (vectorization).\"\n---\n\n# Blazing Fast .NET Performance\n\n> [!WARNING]\n> Much of the advice here might not age well: as .NET evolves, old hacks and custom knobs may become obsolete or even detrimental. Apply only after careful consideration and testing. Revisit periodically to ensure continued relevance.\n\nThis skill focuses on optimizing .NET applications for maximum performance, providing tips, techniques, and best practices to achieve blazing-fast execution times. It targets .NET 10.0 and 11.0. Older versions have not been tested.\n\n**Contents**\n\n- [Profiling and Performance Analysis](#profiling-and-performance-analysis)\n  - [dotnet-counters](#dotnet-counters)\n  - [dotnet-trace](#dotnet-trace)\n  - [Low-level profiling with Linux `perf`](#low-level-profiling-with-linux-perf)\n  - [Popular low-level problems](#popular-low-level-problems)\n  - [Inspecting JIT codegen](#inspecting-jit-codegen)\n- [Best practices for high-performance C# code](#best-practices-for-high-performance-c-code)\n  - [Quick tips](#quick-tips)\n  - [Strings and globalization](#strings-and-globalization)\n  - [Contention on shared state](#contention-on-shared-state)\n    - [False sharing](#false-sharing)\n  - [Safe vectorization (SIMD or SWAR)](#safe-vectorization-simd-or-swar)\n  - [Generic specialization via static abstract members](#generic-specialization-via-static-abstract-members)\n- [ASP.NET Core](#aspnet-core)\n- [Magic knobs to Tune .NET Performance](#magic-knobs-to-tune-net-performance)\n- [NativeAOT-specific tuning](#nativeaot-specific-tuning)\n- [General notes](#general-notes)\n\n# Profiling and Performance Analysis\n\nStart cheap and go deeper only when needed: counters (what kind of bottleneck?) → traces (where?) → `perf` and JIT disassembly.\nInstall the tools with:\n\n```sh\ndotnet tool install -g dotnet-counters\ndotnet tool install -g dotnet-trace\ndotnet tool install -g dotnet-symbol\n```\n\n## dotnet-counters\n\n[dotnet-counters](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fdiagnostics\u002Fdotnet-counters) is a low-overhead, first-level triage tool. Run it while the app is under load:\n\n```sh\ndotnet-counters monitor -p \u003Cpid>                                    # System.Runtime counters by default\ndotnet-counters monitor -p \u003Cpid> --counters System.Runtime,Microsoft.AspNetCore.Hosting,System.Net.Http\ndotnet-counters collect -p \u003Cpid> --format csv -o counters.csv      # save for post-processing\n```\n\nSee the `System.Runtime` [built-in metrics](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fdiagnostics\u002Fbuilt-in-metrics-runtime) (.NET 9+) for what each counter means.\n\n## dotnet-trace\n\n[dotnet-trace](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fdiagnostics\u002Fdotnet-trace) collects EventPipe traces on any OS without root or a native profiler (managed frames only):\n\n```sh\ndotnet-trace collect -p \u003Cpid> --duration 00:00:00:10    # default profiles: dotnet-common + dotnet-sampled-thread-time\ndotnet-trace collect -p \u003Cpid> --profile gc-verbose      # GCs + sampled allocations: which types\u002Fstacks allocate\ndotnet-trace collect -p \u003Cpid> --clrevents contention    # lock contention events with stacks\ndotnet-trace collect -- .\u002FMyApp arg1                    # trace from startup\ndotnet-trace list-profiles\n\ndotnet-trace report trace.nettrace topN -n 20           # top methods (exclusive) as plain text\ndotnet-trace report trace.nettrace topN -n 20 --inclusive\ndotnet-trace convert trace.nettrace --format Speedscope # open in https:\u002F\u002Fwww.speedscope.app\n```\n\nFor more tips on using `dotnet-trace`, refer to the [dotnet-trace collection skill](https:\u002F\u002Fraw.githubusercontent.com\u002Fdotnet\u002Fskills\u002Frefs\u002Fheads\u002Fmain\u002Fplugins\u002Fdotnet-diag\u002Fskills\u002Fdotnet-trace-collect\u002FSKILL.md).\n\n## Low-level profiling with Linux `perf`\n\nThe instructions below are mostly for CoreCLR\u002FJIT scenarios on Linux with the native `perf` tool. NativeAOT\u002FR2R scenarios should presumably work as is, without `perf inject`.\n\nTypically, the following environment variables need to be set in the context of the running application:\n\n```sh\nDOTNET_PerfMapEnabled=1\nDOTNET_PerfMapStubGranularity=3\nDOTNET_JitFramed=1\nDOTNET_EnableWriteXorExecute=0\n```\n\nWhat to profile depends on the scenario. Typically it's steady-state performance, so wait until the process is properly warmed up (e.g. 1 minute), then attach and collect traces:\n\n```sh\nperf record -k 1 -g -F 3999 -p $PROCESS_PID -o perf.data -- sleep 5\n```\nNext, symbolize the collected JIT frames using `perf inject`:\n\n```sh\nperf inject --input perf.data --jit --output perfjit.data\n```\n\nThen use the resulting `perfjit.data` file as needed, e.g. to generate flame graphs or annotated asm:\n\n```sh\n# annotated asm & report:\nperf report --input perfjit.data --no-children --percent-limit 1 --stdio > perf_report.txt\nperf annotate --stdio2 -i perfjit.data --percent-limit 1 -M intel > perf.asm\n\n# Generate flamegraph (svg)\ngit clone --depth 1 --quiet https:\u002F\u002Fgithub.com\u002Fbrendangregg\u002FFlameGraph || true\nperf script -i perfjit.data | .\u002FFlameGraph\u002Fstackcollapse-perf.pl | .\u002FFlameGraph\u002Fflamegraph.pl > flamegraph.svg\n```\n\nNow `perf.asm` contains the annotated assembly output for the hottest methods in your application. Keep in mind that sample attribution is imprecise (\"skid\"): the cost is often reported on an instruction shortly after the one that actually stalls (e.g. right after a slow load or division), so inspect the neighboring instructions too.\n\nIn case of missing symbols you may need to use `dotnet-symbol` to download the necessary debug symbols for .dll\u002F.dylib\u002F.so:\n\n```sh\ndotnet-symbol --symbols $PUBLISH_FOLDER\u002F*.dll\ndotnet-symbol --symbols $PUBLISH_FOLDER\u002F*.so\n```\n\nAll other `perf`-related techniques (e.g. c2c, branch profiling, cache misses) can be applied similarly, depending on the performance aspects you want to analyze.\n\nFor simple functions, create a self-contained console application that calls the function in an infinite loop. For BenchmarkDotNet, use the in-process toolchain (`-i` or `[InProcess]`) with a long iteration duration and a very large iteration count so it is clear which process to attach `perf` to.\n\n## Popular low-level problems\n\n- Cache contention and false sharing in multi-threaded code. Fix with per-thread data and padding (see [False sharing](#false-sharing)).\n- Bounds checks not being elided by the JIT.\n- Store-to-load forwarding stalls, e.g. writing a struct field by field and reading it back with a wider load.\n- Bad data locality causing cache misses.\n- Code alignment noise. Loop or branch placement, Intel JCC erratum - not something we can control, just to keep in mind when analyzing performance variations.\n- GC's alignment is 8 bytes (64-bit), which might not be suitable for SIMD optimizations (e.g. AVX512 might penalize every load\u002Fstore if misaligned since the cache line is 64 bytes).\n\n## Inspecting JIT codegen\n\nThese are diagnostic switches (not tuning knobs) and work with the shipped Release runtime:\n\n```sh\nDOTNET_JitDisasm=\"Test\"            # method list: 'Test', 'Program:Test', '*Test*', 'Program:*' (space-separated)\nDOTNET_JitDisasmSummary=1          # list every jitted method with its tier\nDOTNET_JitStdOutFile=\u002Ftmp\u002Fjit.txt  # write JIT output to a file instead of stdout\nDOTNET_JitDisasmDiffable=1         # stable output (no addresses) for before\u002Fafter diffs\nDOTNET_JitDisasmOnlyOptimized=1    # show only Tier-1\u002FFullOpts code\n```\n^ might require `MethodImplOptions.NoInlining` on the method to ensure it gets JIT-compiled and not inlined away.\n\n> [!TIP]\n> Set them only for the app process, not for `dotnet run`, which would also dump the SDK's own methods.\n\n- A method is compiled several times as it tiers up. Judge the last version: header `; Tier1 code` (or `; Tier1-OSR code` \u002F `; FullOpts code`), ideally with `; optimized using Dynamic PGO`. `; Tier0 code` and `; Instrumented Tier0 code` are unoptimized.\n- BCL methods precompiled with ReadyToRun show up only once they get hot and are re-jitted at Tier1.\n- NativeAOT: pass the same options to ILC, e.g. `\u003CIlcArg Include=\"--codegenopt:JitDisasm=Test\" \u002F>` and `\u003CIlcArg Include=\"--codegenopt:JitStdOutFile=jit.txt\" \u002F>`.\n\n# Best practices for high-performance C# code\n\n> [!IMPORTANT]\n> Only safe C# code is considered in these best practices. Unsafe code is highly discouraged and not covered here.\n\n## Quick tips\n\n- Use [source-generated System.Text.Json](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fserialization\u002Fsystem-text-json\u002Fsource-generation): pass generated `JsonTypeInfo\u003CT>` to avoid reflection-based metadata discovery and enable supported serialization fast paths. Preserve existing serialization options and behavior.\n- Use [`[LoggerMessage]`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fextensions\u002Flogging\u002Fsource-generation) source-generated logging to avoid template parsing, boxing, and temporary allocations. Still guard expensive argument computation with `IsEnabled`.\n- Use [`[GeneratedRegex]`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fbase-types\u002Fregular-expression-source-generators) for compile-time-known patterns instead of runtime pattern compilation. Preserve options, culture, and match timeouts.\n- Prefer optimized bulk APIs over handwritten loops: `Span.CopyTo`, `Clear`, `Fill`, `SequenceEqual`, and `IndexOf` already have specialized implementations, including SIMD where appropriate.\n- Use RVA-backed spans `static ReadOnlySpan\u003Clong> RVA => [1, 2, 3];` for immutable data (only primitives, e.g., `long`, `byte`, `char`) - the data will be embedded into metadata, and the JIT will be able to perform constant folding on it.\n- Prefer static lambdas and state-passing overloads in hot paths to avoid capturing closures.\n- Parse and format UTF-8 directly: numeric `TryParse(ReadOnlySpan\u003Cbyte>, ...)` and `TryFormat(Span\u003Cbyte>, ...)` avoid intermediate strings and UTF-8\u002FUTF-16 transcoding. Preserve culture and formatting semantics.\n- Cache `SearchValues\u003Cchar>` \u002F `SearchValues\u003Cbyte>` for repeated searches against fixed sets; use `SearchValues\u003Cstring>` for multi-substring searches. Construction has a cost, so do not create these per call.\n- Consider `FrozenDictionary` \u002F `FrozenSet` for build-once, read-many data. Their construction cost must be amortized over enough lookups; preserve the intended comparer.\n- Use dictionary alternate lookups from spans: `dictionary.GetAlternateLookup\u003CReadOnlySpan\u003Cchar>>()` avoids allocating temporary string keys when the comparer supports it. Use `TryGetAlternateLookup` when comparer support is not known.\n- Implement `IEquatable\u003CT>` and a good `GetHashCode` for struct dictionary\u002Fset keys. This can avoid expensive default equality paths, boxing, and collision-heavy hashes.\n- Try [`TensorPrimitives`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fapi\u002Fsystem.numerics.tensors.tensorprimitives) before hand-vectorizing numeric operations. Its span-based implementations handle SIMD and tails; prefer it over manual SIMD loops or LINQ for things like finding min\u002Fmax, sums, etc.\n- Prefer [`[LibraryImport]`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fnative-interop\u002Fpinvoke-source-generation) over `[DllImport]` for supported signatures to generate marshalling at build time; both `DllImport` and `LibraryImport` require `AllowUnsafeBlocks=true` under unsafe-v2, but if interop is not avoidable, `LibraryImport` is generally preferred.\n- Use `static readonly` flags for genuinely immutable process-wide configuration. Optimized JIT code can fold their values and eliminate disabled branches.\n- Cache fields in locals in hot loops (`var items = _items;`). The JIT often can't do it for you: calls and stores through references may modify the field, and the memory model restricts hoisting reads. Locals also enable bounds check elimination for arrays\u002Fspans.\n- Consider `Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping` for UTF-8 JSON-only responses ([documentation](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fserialization\u002Fsystem-text-json\u002Fcharacter-encoding#serialize-all-characters)). Never embed its raw output in HTML or `\u003Cscript>`; any custom encoder disables STJ's generated serialization fast path, so benchmark rather than assuming the gains add up.\n- Create `JsonSerializerOptions` once and reuse it (CA1869). A new instance with the same settings still pays a global cache lookup; one that also creates converter instances (`Converters = { new JsonStringEnumConverter() }`) misses that cache, since converters compare by reference, and rebuilds metadata for every type it touches on each call.\n- For most bit\u002Fbyte manipulations, prefer the built-in `BitOperations`, `BinaryPrimitives`, `BitConverter` or static numeric helpers such as `uint.Log2`, `uint.PopCount`, `uint.TrailingZeroCount`, etc.\n- Span\u002FReadOnlySpan have a lot of useful extension methods via `MemoryExtensions` such as `SequenceEqual`, `IndexOf`, `IndexOfAnyExcept`, `LastIndexOf`, `StartsWith`, `CommonPrefixLength`, and a lot more - prefer these APIs over manual loops or vectorization.\n- Don't pin benchmarks to a single core - doing so might significantly affect internal VM heuristics (e.g. tiered compilation timing).\n- For BenchmarkDotNet methodology, see the [dotnet\u002Fruntime microbenchmark skill](https:\u002F\u002Fgithub.com\u002Fdotnet\u002Fruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fmicrobenchmark\u002FSKILL.md).\n- `AggressiveOptimization` is usually a deoptimization.\n- Overusing `AggressiveInlining` may hurt performance (e.g. by exhausting the inliner's time budget or increasing the number of tracked local variables).\n- Moving rarely taken paths (grow\u002Fresize, slow fallback) into a separate method marked with  `[MethodImpl(MethodImplOptions.NoInlining)]` may improve performance (as `List\u003CT>.Add` does with `AddWithResize`), but it may also hinder escape analysis.\n- Don't put too much data into TLS (Thread-Local Storage) - excessive use can lead to increased memory usage and cache pressure, reducing overall performance (there can be a lot of threads, each with its own copy).\n- Consider `CollectionsMarshal.AsSpan(list)` for `List\u003CT>` (there is no `List\u003CT>.AsSpan()`), or `.AsSpan()` on collections that support it, to avoid unnecessary overhead from bound and covariance checks, and to enable span-based algorithms directly on the collection's underlying memory. Don't add or remove list items while the span is in use.\n- Prefer XXH3 via Microsoft's `System.IO.Hashing.XxHash3` for fast fingerprinting of large blobs. Use `XxHash128` when 128-bit fingerprints are needed. For exact deduplication, verify matches byte for byte. Use cryptographic hashes when security requires them. NOTE: Be careful with data that may contain garbage or uninitialized bytes (e.g. arrays of structs with padding).\n\n## Strings and globalization\n\n- Prefer ordinal operations. Culture-sensitive comparisons go through ICU, are many times slower than ordinal ones, and are often a correctness bug anyway.\n- Culture-sensitive by default: `string.Compare`, `CompareTo`, `StartsWith(string)`, `EndsWith(string)`, `IndexOf(string)`, `LastIndexOf(string)`, `ToUpper()`, `ToLower()`, and default string sorting (`Array.Sort`, `List\u003CT>.Sort`, `OrderBy`, `SortedDictionary`\u002F`SortedSet` with the default comparer). Pass `StringComparison.Ordinal`\u002F`OrdinalIgnoreCase` or `StringComparer.Ordinal`; analyzers CA1307, CA1309 and CA1310 find these calls.\n- Already ordinal: `==`, `Equals`, `Contains(string)`, `Replace(string, string)`, `IndexOf(char)`, `Split`, `GetHashCode`, and the default `Dictionary`\u002F`HashSet` comparer.\n- Case-insensitive equality: `string.Equals(a, b, StringComparison.OrdinalIgnoreCase)` instead of `a.ToLower() == b.ToLower()` (two allocations plus culture rules). For ASCII data, `System.Text.Ascii` has vectorized `EqualsIgnoreCase`, `ToUpper`\u002F`ToLower` (span to span) and `IsValid`.\n- `Dictionary\u003Cstring, T>` \u002F `HashSet\u003Cstring>` use fast non-randomized hashing only with the default comparer, `StringComparer.Ordinal` or `StringComparer.OrdinalIgnoreCase` (falling back to randomized hashing only on heavy collisions). Any other comparer loses it.\n- Stay in UTF-8 when input and output are UTF-8: search, parse and format `ReadOnlySpan\u003Cbyte>` directly (`u8` literals, `SearchValues\u003Cbyte>`, `TryParse`\u002F`TryFormat` on bytes, `Utf8.TryWrite`) and convert to `string` only when needed.\n- If the app needs no culture data, `\u003CInvariantGlobalization>true\u003C\u002FInvariantGlobalization>` removes the ICU dependency (faster startup, less memory) and makes culture-sensitive string operations ordinal. This changes behavior, so verify the output.\n\n## Contention on shared state\n\nWrites to one shared location from many threads (`Interlocked.Increment` on a global counter, a shared \"total\" field, etc.) serialize all of them on a single cache line, so throughput can get *worse* as cores are added. Split the state, update only the local part, and combine on read. Two options:\n\n**1. Per-core stripes** - index an array by `Thread.GetCurrentProcessorId()` (cheap: cached and periodically refreshed). The id is only a hint: threads migrate, and ids can exceed `ProcessorCount` (hence the modulo), so keep `Interlocked` on the stripe - it's almost always uncontended. Fixed memory and allocation-free reads; works with any number of threads (thread pool, request handlers). Stripes must be padded, see [False sharing](#false-sharing).\n\n```cs\nsealed class StripedCounter\n{\n    private readonly PaddedLong[] _stripes = new PaddedLong[Environment.ProcessorCount];\n\n    public void Increment()\n    {\n        PaddedLong[] stripes = _stripes;\n        Interlocked.Increment(ref stripes[(uint)Thread.GetCurrentProcessorId() % (uint)stripes.Length].Value);\n    }\n\n    \u002F\u002F Not an atomic snapshot, which is fine for statistics.\n    public long Sum()\n    {\n        PaddedLong[] stripes = _stripes;\n        long sum = 0;\n        for (int i = 0; i \u003C stripes.Length; i++)\n            sum += Volatile.Read(ref stripes[i].Value);\n        return sum;\n    }\n}\n```\n\n**2. `ThreadLocal\u003CT>` with `trackAllValues: true`** - each thread updates its own slot with no atomics at all; sum `Values` on read. `Values` allocates a list and includes values of threads that have already exited, and every thread that ever touched it keeps a slot, so this suits a bounded set of long-lived threads (e.g. `Parallel` workers) where writes vastly outnumber reads. Dispose the `ThreadLocal\u003CT>` when done.\n\n```cs\nprivate readonly ThreadLocal\u003Clong> _count = new(trackAllValues: true);\n\nvoid OnItem() => _count.Value++;\nlong Total() => _count.Values.Sum();\n```\n\nIf the work structure allows it, aggregating into plain locals and combining once per task\u002Fpartition (`Parallel.For` with `localInit`\u002F`localFinally`) is cheaper than both.\n\n### False sharing\n\nThreads writing *different* variables still contend if those variables share a cache line (64 bytes on most x64\u002Farm64 CPUs, 128 bytes on Apple M-series): every write invalidates the line in the other cores' caches. The naive striped counter is the classic case:\n\n```cs\n\u002F\u002F 8 longs per 64-byte line: the per-core slots look independent, but cores keep stealing the line from each other.\nlong[] stripes = new long[Environment.ProcessorCount];\nInterlocked.Increment(ref stripes[(uint)Thread.GetCurrentProcessorId() % (uint)stripes.Length]);\n```\n\nFix it by padding each slot so no two hot values can land on the same line:\n\n```cs\nstruct PaddedLong\n{\n    public long Value;\n#pragma warning disable CS0169 \u002F\u002F padding only\n    private InlineArray8\u003Clong> _padding; \u002F\u002F 64 bytes: adjacent Values are 72 bytes apart\n#pragma warning restore CS0169\n}\n```\n\n- Most server hardware (all x64 CPUs and Neoverse-based arm64 CPUs such as Cobalt and Graviton) has 64-byte cache lines, so 64 bytes of padding is usually sufficient. Apple M-series CPUs have 128-byte cache lines, so consider padding to 128 bytes there.\n- The same applies to fields of one object written by different threads (e.g. a ring buffer's head and tail indices): put a padding field between them.\n\n## Safe vectorization (SIMD or SWAR)\n\nIn .NET 11.0 the JIT got improvements in bounds check elimination and now recognizes the following shape for safely loading and processing multiple elements from an array\u002Fspan:\n\n```cs\nwhile (data.Length >= CNS)\n{\n    \u002F\u002F JIT knows that the slice has at least CNS elements, so bounds checks can be elided.\n    \u002F\u002F e.g.:\n    \u002F\u002F  VectorX.Create(data);\n    \u002F\u002F  BitConverter.ToInt32(data);\n    \u002F\u002F  BinaryPrimitives.ReadInt32LittleEndian(data);\n    \u002F\u002F  etc.\n    data = data.Slice(CNS);\n}\n```\n\nFor example, the following C# snippet has no bounds checks in .NET 11.0:\n\n```cs\nint Sum(Span\u003Cint> data)\n{\n    Vector128\u003Cint> sum = default;\n    while (data.Length >= Vector128\u003Cint>.Count)\n    {\n        sum += Vector128.Create(data);\n        data = data.Slice(Vector128\u003Cint>.Count);\n    }\n    int result = Vector128.Sum(sum);\n    foreach (var t in data)\n        result += t;\n    return result;\n}\n```\n\n.NET 12.0 (Preview 1 or main) extends it to more complex loop shapes (e.g. multiple spans):\n\n```cs\nstatic bool Equal(ReadOnlySpan\u003Cushort> a, ReadOnlySpan\u003Cushort> b)\n{\n    if (a.Length != b.Length)\n        return false;\n\n    int i = 0;\n    if (Vector128.IsHardwareAccelerated)\n    {\n        for (; i \u003C= a.Length - Vector128\u003Cushort>.Count; i += Vector128\u003Cushort>.Count)\n        {\n            var va = Vector128.Create(a.Slice(i));\n            var vb = Vector128.Create(b.Slice(i));\n            if (va != vb)\n                return false;\n        }\n    }\n\n    for (; i \u003C a.Length; i++)\n    {\n        if (a[i] != b[i])\n            return false;\n    }\n\n    return true;\n}\n```\n^ has no bounds checks for the main loop in .NET 12.0 (Preview 1).\n\n> [!TIP]\n> This only illustrates the loop shape. For this exact task, just call `a.SequenceEqual(b)`.\n\nMore info about vectorization and SIMD in .NET can be found in the [official documentation](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fstandard\u002Fsimd). Also consider using [TensorPrimitives](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fapi\u002Fsystem.numerics.tensors.tensorprimitives).\n\n## Generic specialization via static abstract members\n\nStatic abstract interface members let you specialize a generic method for values supplied by struct tags, without duplicating its source code. The JIT generates separate native versions of `Big\u003CC42>` and `Big\u003CC100>`. In optimized code, it can inline the small `Value` getters and fold expressions and branches that use `T.Value`. This works even when `Big\u003CT>` itself is too large to inline; The tradeoff is increased native code size. `T.Value` is not a C# compile-time constant: constant folding depends on JIT optimizations and getter inlining.\n\n```cs\nusing System.Runtime.CompilerServices;\n\ninterface IConstant {\n    static abstract int Value { get; }\n}\n\nreadonly struct C42 : IConstant {\n    public static int Value => 42;\n}\n\nreadonly struct C100 : IConstant {\n    public static int Value => 100;\n}\n\nstatic class Example\n{\n    static int Big\u003CT>(int x) where T : struct, IConstant\n    {\n        int arg = T.Value;\n\n        \u002F\u002F The large body would go here.\n\n        return arg == 42 ? x * arg : x + arg;\n    }\n\n    static int Use42(int x) => Big\u003CC42>(x);\n    static int Use100(int x) => Big\u003CC100>(x);\n}\n```\n\nIt is also handy for scenarios where you want to leverage different vector sizes or constants in a generic way, allowing the JIT to generate optimized code for each specialization without duplicating the method's source code. Example: summing an array using different vector widths with static abstract members.\n\n```cs\nusing System;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\n\nclass Program\n{\n    static void Main()\n    {\n        int[] values = new int[1003];\n\n        if (Vector128.IsHardwareAccelerated)\n            Console.WriteLine(Sum\u003CVector128\u003Cint>, Ops128>(values));\n        if (Vector256.IsHardwareAccelerated)\n            Console.WriteLine(Sum\u003CVector256\u003Cint>, Ops256>(values));\n        if (Vector512.IsHardwareAccelerated) \n            Console.WriteLine(Sum\u003CVector512\u003Cint>, Ops512>(values));\n    }\n\n    [MethodImpl(MethodImplOptions.NoInlining)]\n    static int Sum\u003CV, TOps>(ReadOnlySpan\u003Cint> s)\n        where V : struct\n        where TOps : struct, IOps\u003CV>\n    {\n        V acc = default;\n        int count = TOps.Count;\n\n        while (s.Length >= count)\n        {\n            acc = TOps.Add(acc, TOps.Load(s));\n            s = s.Slice(count);\n        }\n\n        int sum = TOps.Sum(acc);\n        foreach (int x in s) sum = unchecked(sum + x);\n        return sum;\n    }\n}\n\n\ninterface IOps\u003CV> where V : struct\n{\n    static abstract int Count { get; }\n    static abstract V Load(ReadOnlySpan\u003Cint> s);\n    static abstract V Add(V a, V b);\n    static abstract int Sum(V v);\n}\n\nreadonly struct Ops128 : IOps\u003CVector128\u003Cint>>\n{\n    public static int Count => Vector128\u003Cint>.Count;\n    public static Vector128\u003Cint> Load(ReadOnlySpan\u003Cint> s) => Vector128.Create(s);\n    public static Vector128\u003Cint> Add(Vector128\u003Cint> a, Vector128\u003Cint> b) => a + b;\n    public static int Sum(Vector128\u003Cint> v) => Vector128.Sum(v);\n}\n\nreadonly struct Ops256 : IOps\u003CVector256\u003Cint>>\n{\n    public static int Count => Vector256\u003Cint>.Count;\n    public static Vector256\u003Cint> Load(ReadOnlySpan\u003Cint> s) => Vector256.Create(s);\n    public static Vector256\u003Cint> Add(Vector256\u003Cint> a, Vector256\u003Cint> b) => a + b;\n    public static int Sum(Vector256\u003Cint> v) => Vector256.Sum(v);\n}\n\nreadonly struct Ops512 : IOps\u003CVector512\u003Cint>>\n{\n    public static int Count => Vector512\u003Cint>.Count;\n    public static Vector512\u003Cint> Load(ReadOnlySpan\u003Cint> s) => Vector512.Create(s);\n    public static Vector512\u003Cint> Add(Vector512\u003Cint> a, Vector512\u003Cint> b) => a + b;\n    public static int Sum(Vector512\u003Cint> v) => Vector512.Sum(v);\n}\n```\n\n# ASP.NET Core\n\nCode-level advice for HTTP throughput benchmarks.\n\n- Start from `WebApplication.CreateSlimBuilder(args)` (or `CreateEmptyBuilder` + `builder.WebHost.UseKestrelCore()`) and add only what's needed. Every middleware component (HTTPS redirection, auth, CORS, response compression, static files, developer exception page) costs something per request.\n- Logging: without an `appsettings.json` that raises `Microsoft.AspNetCore` to `Warning`, the default level is `Information` and the host logs every request to the console - a massive bottleneck. Call `builder.Logging.ClearProviders()` or raise the level.\n- JSON: register source-generated metadata with `builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));`. For hand-written responses, serialize with a reused `Utf8JsonWriter` (`writer.Reset(response.BodyWriter)`) instead of allocating one per request.\n\n# Magic knobs to Tune .NET Performance\n\n> [!WARNING]\n> It is highly recommended to keep the default settings unless you have measured and understood the performance implications of changing them. \n\nMost of these knobs are relevant only for server workloads or performance-critical scenarios. They're not applicable for general-purpose libraries.\n\n⭐ - known to have a visible impact on performance (typically, in synthetic benchmarks).\n\n| Environment variable (CoreCLR Release, .NET 10.0+) | Default | Values to try | Purpose and trade-offs |\n| --- | --- | --- | --- |\n| ⭐`DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS` | `0` | `1` | Run I\u002FO continuations directly on poller threads instead of dispatching them to workers - beneficial for workloads with many small requests. ⚠️ Blocking or lengthy continuations can stall I\u002FO ⚠️ |\n| ⭐`DOTNET_ThreadPool_UnfairSemaphoreSpinLimit` | `70` in .NET 10.0; `1024` in current .NET 11.0 | `0`, `0x400`, `0xC00` | Trade worker wake latency against CPU spent spinning. `0` might be useful as a mitigation for high CPU usage (especially on arm64) at the cost of throughput. Large values might improve synthetic benchmark performance. |\n| ⭐`DOTNET_GCDynamicAdaptationMode` | `1` | `0` | Disable DATAS for server GC. Can improve throughput at the expense of memory; compare against tuning DATAS (e.g. `DOTNET_GCDGen0GrowthPercent`) rather than disabling it. |\n| ⭐`DOTNET_HillClimbing_Disable` | `0` | `1` | Disable ThreadPool hill climbing (improves time to steady state). |\n| `DOTNET_SYSTEM_NET_SOCKETS_THREAD_COUNT` | Automatic; processor count when inline completions are enabled | `1`, `2`, `4`, `8`, up to processor count | Tune I\u002FO poller count. Fewer pollers can reduce scheduling and cache overhead; too few can serialize processing. Values are decimal. |\n| `DOTNET_gcServer` | varies by environment | `1` | Typically enabled by default for server workloads. Might improve the performance of desktop\u002Fconsole tools. |\n| `DOTNET_GCDTargetTCP` | Effective target `2%` (configuration `0`) | `1` | Lower DATAS's target throughput-cost percentage. Encourages more heaps when GC cost exceeds the target. Only relevant with DATAS enabled. |\n| `DOTNET_GCDGen0GrowthPercent` | Effective multiplier `100%` (configuration `0`) | `0xC8` | Scale DATAS's gen0 budget multiplier to 200% of its default. Trades memory for potentially fewer collections. Only relevant with DATAS enabled. |\n| `DOTNET_TC_CallCountingDelayMs` | `100` ms; longer on a single processor | `0` | Only for short-lived console tools where JIT warmup takes too long: remove the tiering delay while retaining the normal call-count threshold. Can increase compilation work early in execution. |\n| `DOTNET_TieredCompilation` | `1` | `0` | Alternative for short-lived console tools where JIT warmup takes too long: disable tiering and JIT optimized code on first use. Removes tiered warmup but disables dynamic PGO and can increase initial JIT cost. |\n\nUsing NativeAOT or disabling tiered compilation via `DOTNET_TC_CallCountingDelayMs=0`\u002F`DOTNET_TieredPGO=0`\u002F`DOTNET_TieredCompilation=0` may significantly improve performance for short-lived console tools or benchmarks that measure the entire process rather than just steady-state execution.\n\n# NativeAOT-specific tuning\n\nRecommended reading: Microsoft's [Optimizing AOT deployments](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fcore\u002Fdeploying\u002Fnative-aot\u002Foptimizing) article, plus the runtime's [CPU instruction-set tuning guide](https:\u002F\u002Fgithub.com\u002Fdotnet\u002Fruntime\u002Fblob\u002F9da219572c1\u002Fsrc\u002Fcoreclr\u002Fnativeaot\u002Fdocs\u002Foptimizing.md). The latter describes implementation-specific options that can change between SDK versions.\n\n> [!NOTE]\n> These are publish-time MSBuild properties: republish for each experiment. NativeAOT has no JIT or tiered compilation, so the CoreCLR JIT\u002Ftiering environment variables above do not apply.\n\n| MSBuild setting | Purpose and trade-offs |\n| --- | --- |\n| `-p:OptimizationPreference=Speed` | Optimize for execution time (`--Ot`) instead of the default size\u002Fspeed balance. A good throughput experiment, but can increase executable size and instruction-cache pressure. |\n| `-p:OptimizationPreference=Size` | Optimize for executable size (`--Os`). Useful when distribution size or memory footprint matters more than peak throughput; measure the speed trade-off. |\n| `-p:IlcInstructionSet=native` | Target instruction sets supported by the build machine's CPU. Useful for local benchmarks or homogeneous deployments; no cross-architecture compilation support, and the executable may not run on older CPUs. Use an explicit instruction-set baseline for heterogeneous deployments. |\n| `-p:IlcInstructionSet=armv8.1-a` | If `IlcInstructionSet=native` is not acceptable for you, consider explicitly raising the baseline from ARMv8.0-A to ARMv8.1-A to include LSE (crucial for atomics-heavy workloads). |\n\n```sh\ndotnet publish -c Release -r linux-arm64 -p:PublishAot=true -p:OptimizationPreference=Speed -p:IlcInstructionSet=native\n```\n\n# General notes\n\n- Consider filing a [dotnet\u002Fruntime](https:\u002F\u002Fgithub.com\u002Fdotnet\u002Fruntime\u002Fissues) issue only for a clear, reproducible missed optimization in the JIT or libraries with meaningful measured impact. Check for duplicates, include a minimal repro and measurements, and obtain the user's approval before filing.\n- Compare equivalent execution plans before blaming the language. Consider pairwise comparisons, stronger filtering, and verification requirements before tuning code generation.\n- Don't draw conclusions about workloads from tiny synthetic benchmark results.","# Blazing Fast .NET Performance\n\n> [!WARNING]\n> Much of the advice here might not age well: as .NET evolves, old hacks and custom knobs may become obsolete or even detrimental. Apply only after careful consideration and testing. Revisit periodically to ensure continued relevance.\n\nThis skill focuses on optimizing .NET applications for maximum performance, providing tips, techniques, and best practices to achieve blazing-fast execution times. It targets .NET 10.0 and 11.0. Older versions have not been tested.\n\n**Contents**\n\n- [Profiling and Performance Analysis](#profiling-and-performance-analysis)\n  - [dotnet-counters](#dotnet-counters)\n  - [dotnet-trace](#dotnet-trace)\n  - [Low-level profiling with Linux `perf`](#low-level-profiling-with-linux-perf)\n  - [Popular low-level problems](#popular-low-level-problems)\n  - [Inspecting JIT codegen](#inspecting-jit-codegen)\n- [Best practices for high-performance C# code](#best-practices-for-high-performance-c-code)\n  - [Quick tips](#quick-tips)\n  - [Strings and globalization](#strings-and-globalization)\n  - [Contention on shared state](#contention-on-shared-state)\n    - [False sharing](#false-sharing)\n  - [Safe vectorization (SIMD or SWAR)](#safe-vectorization-simd-or-swar)\n  - [Generic specialization via static abstract members](#generic-specialization-via-static-abstract-members)\n- [ASP.NET Core](#aspnet-core)\n- [Magic knobs to Tune .NET Performance](#magic-knobs-to-tune-net-performance)\n- [NativeAOT-specific tuning](#nativeaot-specific-tuning)\n- [General notes](#general-notes)\n\n# Profiling and Performance Analysis\n\nStart cheap and go deeper only when needed: counters (what kind of bottleneck?) → traces (where?) → `perf` and JIT disassembly.\nInstall the tools with:\n\n```sh\ndotnet tool install -g dotnet-counters\ndotnet tool install -g dotnet-trace\ndotnet tool install -g dotnet-symbol\n```\n\n## dotnet-counters\n\n[dotnet-counters](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fdiagnostics\u002Fdotnet-counters) is a low-overhead, first-level triage tool. Run it while the app is under load:\n\n```sh\ndotnet-counters monitor -p \u003Cpid>                                    # System.Runtime counters by default\ndotnet-counters monitor -p \u003Cpid> --counters System.Runtime,Microsoft.AspNetCore.Hosting,System.Net.Http\ndotnet-counters collect -p \u003Cpid> --format csv -o counters.csv      # save for post-processing\n```\n\nSee the `System.Runtime` [built-in metrics](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fdiagnostics\u002Fbuilt-in-metrics-runtime) (.NET 9+) for what each counter means.\n\n## dotnet-trace\n\n[dotnet-trace](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fdiagnostics\u002Fdotnet-trace) collects EventPipe traces on any OS without root or a native profiler (managed frames only):\n\n```sh\ndotnet-trace collect -p \u003Cpid> --duration 00:00:00:10    # default profiles: dotnet-common + dotnet-sampled-thread-time\ndotnet-trace collect -p \u003Cpid> --profile gc-verbose      # GCs + sampled allocations: which types\u002Fstacks allocate\ndotnet-trace collect -p \u003Cpid> --clrevents contention    # lock contention events with stacks\ndotnet-trace collect -- .\u002FMyApp arg1                    # trace from startup\ndotnet-trace list-profiles\n\ndotnet-trace report trace.nettrace topN -n 20           # top methods (exclusive) as plain text\ndotnet-trace report trace.nettrace topN -n 20 --inclusive\ndotnet-trace convert trace.nettrace --format Speedscope # open in https:\u002F\u002Fwww.speedscope.app\n```\n\nFor more tips on using `dotnet-trace`, refer to the [dotnet-trace collection skill](https:\u002F\u002Fraw.githubusercontent.com\u002Fdotnet\u002Fskills\u002Frefs\u002Fheads\u002Fmain\u002Fplugins\u002Fdotnet-diag\u002Fskills\u002Fdotnet-trace-collect\u002FSKILL.md).\n\n## Low-level profiling with Linux `perf`\n\nThe instructions below are mostly for CoreCLR\u002FJIT scenarios on Linux with the native `perf` tool. NativeAOT\u002FR2R scenarios should presumably work as is, without `perf inject`.\n\nTypically, the following environment variables need to be set in the context of the running application:\n\n```sh\nDOTNET_PerfMapEnabled=1\nDOTNET_PerfMapStubGranularity=3\nDOTNET_JitFramed=1\nDOTNET_EnableWriteXorExecute=0\n```\n\nWhat to profile depends on the scenario. Typically it's steady-state performance, so wait until the process is properly warmed up (e.g. 1 minute), then attach and collect traces:\n\n```sh\nperf record -k 1 -g -F 3999 -p $PROCESS_PID -o perf.data -- sleep 5\n```\nNext, symbolize the collected JIT frames using `perf inject`:\n\n```sh\nperf inject --input perf.data --jit --output perfjit.data\n```\n\nThen use the resulting `perfjit.data` file as needed, e.g. to generate flame graphs or annotated asm:\n\n```sh\n# annotated asm & report:\nperf report --input perfjit.data --no-children --percent-limit 1 --stdio > perf_report.txt\nperf annotate --stdio2 -i perfjit.data --percent-limit 1 -M intel > perf.asm\n\n# Generate flamegraph (svg)\ngit clone --depth 1 --quiet https:\u002F\u002Fgithub.com\u002Fbrendangregg\u002FFlameGraph || true\nperf script -i perfjit.data | .\u002FFlameGraph\u002Fstackcollapse-perf.pl | .\u002FFlameGraph\u002Fflamegraph.pl > flamegraph.svg\n```\n\nNow `perf.asm` contains the annotated assembly output for the hottest methods in your application. Keep in mind that sample attribution is imprecise (\"skid\"): the cost is often reported on an instruction shortly after the one that actually stalls (e.g. right after a slow load or division), so inspect the neighboring instructions too.\n\nIn case of missing symbols you may need to use `dotnet-symbol` to download the necessary debug symbols for .dll\u002F.dylib\u002F.so:\n\n```sh\ndotnet-symbol --symbols $PUBLISH_FOLDER\u002F*.dll\ndotnet-symbol --symbols $PUBLISH_FOLDER\u002F*.so\n```\n\nAll other `perf`-related techniques (e.g. c2c, branch profiling, cache misses) can be applied similarly, depending on the performance aspects you want to analyze.\n\nFor simple functions, create a self-contained console application that calls the function in an infinite loop. For BenchmarkDotNet, use the in-process toolchain (`-i` or `[InProcess]`) with a long iteration duration and a very large iteration count so it is clear which process to attach `perf` to.\n\n## Popular low-level problems\n\n- Cache contention and false sharing in multi-threaded code. Fix with per-thread data and padding (see [False sharing](#false-sharing)).\n- Bounds checks not being elided by the JIT.\n- Store-to-load forwarding stalls, e.g. writing a struct field by field and reading it back with a wider load.\n- Bad data locality causing cache misses.\n- Code alignment noise. Loop or branch placement, Intel JCC erratum - not something we can control, just to keep in mind when analyzing performance variations.\n- GC's alignment is 8 bytes (64-bit), which might not be suitable for SIMD optimizations (e.g. AVX512 might penalize every load\u002Fstore if misaligned since the cache line is 64 bytes).\n\n## Inspecting JIT codegen\n\nThese are diagnostic switches (not tuning knobs) and work with the shipped Release runtime:\n\n```sh\nDOTNET_JitDisasm=\"Test\"            # method list: 'Test', 'Program:Test', '*Test*', 'Program:*' (space-separated)\nDOTNET_JitDisasmSummary=1          # list every jitted method with its tier\nDOTNET_JitStdOutFile=\u002Ftmp\u002Fjit.txt  # write JIT output to a file instead of stdout\nDOTNET_JitDisasmDiffable=1         # stable output (no addresses) for before\u002Fafter diffs\nDOTNET_JitDisasmOnlyOptimized=1    # show only Tier-1\u002FFullOpts code\n```\n^ might require `MethodImplOptions.NoInlining` on the method to ensure it gets JIT-compiled and not inlined away.\n\n> [!TIP]\n> Set them only for the app process, not for `dotnet run`, which would also dump the SDK's own methods.\n\n- A method is compiled several times as it tiers up. Judge the last version: header `; Tier1 code` (or `; Tier1-OSR code` \u002F `; FullOpts code`), ideally with `; optimized using Dynamic PGO`. `; Tier0 code` and `; Instrumented Tier0 code` are unoptimized.\n- BCL methods precompiled with ReadyToRun show up only once they get hot and are re-jitted at Tier1.\n- NativeAOT: pass the same options to ILC, e.g. `\u003CIlcArg Include=\"--codegenopt:JitDisasm=Test\" \u002F>` and `\u003CIlcArg Include=\"--codegenopt:JitStdOutFile=jit.txt\" \u002F>`.\n\n# Best practices for high-performance C# code\n\n> [!IMPORTANT]\n> Only safe C# code is considered in these best practices. Unsafe code is highly discouraged and not covered here.\n\n## Quick tips\n\n- Use [source-generated System.Text.Json](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fserialization\u002Fsystem-text-json\u002Fsource-generation): pass generated `JsonTypeInfo\u003CT>` to avoid reflection-based metadata discovery and enable supported serialization fast paths. Preserve existing serialization options and behavior.\n- Use [`[LoggerMessage]`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fcore\u002Fextensions\u002Flogging\u002Fsource-generation) source-generated logging to avoid template parsing, boxing, and temporary allocations. Still guard expensive argument computation with `IsEnabled`.\n- Use [`[GeneratedRegex]`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fbase-types\u002Fregular-expression-source-generators) for compile-time-known patterns instead of runtime pattern compilation. Preserve options, culture, and match timeouts.\n- Prefer optimized bulk APIs over handwritten loops: `Span.CopyTo`, `Clear`, `Fill`, `SequenceEqual`, and `IndexOf` already have specialized implementations, including SIMD where appropriate.\n- Use RVA-backed spans `static ReadOnlySpan\u003Clong> RVA => [1, 2, 3];` for immutable data (only primitives, e.g., `long`, `byte`, `char`) - the data will be embedded into metadata, and the JIT will be able to perform constant folding on it.\n- Prefer static lambdas and state-passing overloads in hot paths to avoid capturing closures.\n- Parse and format UTF-8 directly: numeric `TryParse(ReadOnlySpan\u003Cbyte>, ...)` and `TryFormat(Span\u003Cbyte>, ...)` avoid intermediate strings and UTF-8\u002FUTF-16 transcoding. Preserve culture and formatting semantics.\n- Cache `SearchValues\u003Cchar>` \u002F `SearchValues\u003Cbyte>` for repeated searches against fixed sets; use `SearchValues\u003Cstring>` for multi-substring searches. Construction has a cost, so do not create these per call.\n- Consider `FrozenDictionary` \u002F `FrozenSet` for build-once, read-many data. Their construction cost must be amortized over enough lookups; preserve the intended comparer.\n- Use dictionary alternate lookups from spans: `dictionary.GetAlternateLookup\u003CReadOnlySpan\u003Cchar>>()` avoids allocating temporary string keys when the comparer supports it. Use `TryGetAlternateLookup` when comparer support is not known.\n- Implement `IEquatable\u003CT>` and a good `GetHashCode` for struct dictionary\u002Fset keys. This can avoid expensive default equality paths, boxing, and collision-heavy hashes.\n- Try [`TensorPrimitives`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fapi\u002Fsystem.numerics.tensors.tensorprimitives) before hand-vectorizing numeric operations. Its span-based implementations handle SIMD and tails; prefer it over manual SIMD loops or LINQ for things like finding min\u002Fmax, sums, etc.\n- Prefer [`[LibraryImport]`](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fnative-interop\u002Fpinvoke-source-generation) over `[DllImport]` for supported signatures to generate marshalling at build time; both `DllImport` and `LibraryImport` require `AllowUnsafeBlocks=true` under unsafe-v2, but if interop is not avoidable, `LibraryImport` is generally preferred.\n- Use `static readonly` flags for genuinely immutable process-wide configuration. Optimized JIT code can fold their values and eliminate disabled branches.\n- Cache fields in locals in hot loops (`var items = _items;`). The JIT often can't do it for you: calls and stores through references may modify the field, and the memory model restricts hoisting reads. Locals also enable bounds check elimination for arrays\u002Fspans.\n- Consider `Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping` for UTF-8 JSON-only responses ([documentation](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fstandard\u002Fserialization\u002Fsystem-text-json\u002Fcharacter-encoding#serialize-all-characters)). Never embed its raw output in HTML or `\u003Cscript>`; any custom encoder disables STJ's generated serialization fast path, so benchmark rather than assuming the gains add up.\n- Create `JsonSerializerOptions` once and reuse it (CA1869). A new instance with the same settings still pays a global cache lookup; one that also creates converter instances (`Converters = { new JsonStringEnumConverter() }`) misses that cache, since converters compare by reference, and rebuilds metadata for every type it touches on each call.\n- For most bit\u002Fbyte manipulations, prefer the built-in `BitOperations`, `BinaryPrimitives`, `BitConverter` or static numeric helpers such as `uint.Log2`, `uint.PopCount`, `uint.TrailingZeroCount`, etc.\n- Span\u002FReadOnlySpan have a lot of useful extension methods via `MemoryExtensions` such as `SequenceEqual`, `IndexOf`, `IndexOfAnyExcept`, `LastIndexOf`, `StartsWith`, `CommonPrefixLength`, and a lot more - prefer these APIs over manual loops or vectorization.\n- Don't pin benchmarks to a single core - doing so might significantly affect internal VM heuristics (e.g. tiered compilation timing).\n- For BenchmarkDotNet methodology, see the [dotnet\u002Fruntime microbenchmark skill](https:\u002F\u002Fgithub.com\u002Fdotnet\u002Fruntime\u002Fblob\u002Fmain\u002F.github\u002Fskills\u002Fmicrobenchmark\u002FSKILL.md).\n- `AggressiveOptimization` is usually a deoptimization.\n- Overusing `AggressiveInlining` may hurt performance (e.g. by exhausting the inliner's time budget or increasing the number of tracked local variables).\n- Moving rarely taken paths (grow\u002Fresize, slow fallback) into a separate method marked with  `[MethodImpl(MethodImplOptions.NoInlining)]` may improve performance (as `List\u003CT>.Add` does with `AddWithResize`), but it may also hinder escape analysis.\n- Don't put too much data into TLS (Thread-Local Storage) - excessive use can lead to increased memory usage and cache pressure, reducing overall performance (there can be a lot of threads, each with its own copy).\n- Consider `CollectionsMarshal.AsSpan(list)` for `List\u003CT>` (there is no `List\u003CT>.AsSpan()`), or `.AsSpan()` on collections that support it, to avoid unnecessary overhead from bound and covariance checks, and to enable span-based algorithms directly on the collection's underlying memory. Don't add or remove list items while the span is in use.\n- Prefer XXH3 via Microsoft's `System.IO.Hashing.XxHash3` for fast fingerprinting of large blobs. Use `XxHash128` when 128-bit fingerprints are needed. For exact deduplication, verify matches byte for byte. Use cryptographic hashes when security requires them. NOTE: Be careful with data that may contain garbage or uninitialized bytes (e.g. arrays of structs with padding).\n\n## Strings and globalization\n\n- Prefer ordinal operations. Culture-sensitive comparisons go through ICU, are many times slower than ordinal ones, and are often a correctness bug anyway.\n- Culture-sensitive by default: `string.Compare`, `CompareTo`, `StartsWith(string)`, `EndsWith(string)`, `IndexOf(string)`, `LastIndexOf(string)`, `ToUpper()`, `ToLower()`, and default string sorting (`Array.Sort`, `List\u003CT>.Sort`, `OrderBy`, `SortedDictionary`\u002F`SortedSet` with the default comparer). Pass `StringComparison.Ordinal`\u002F`OrdinalIgnoreCase` or `StringComparer.Ordinal`; analyzers CA1307, CA1309 and CA1310 find these calls.\n- Already ordinal: `==`, `Equals`, `Contains(string)`, `Replace(string, string)`, `IndexOf(char)`, `Split`, `GetHashCode`, and the default `Dictionary`\u002F`HashSet` comparer.\n- Case-insensitive equality: `string.Equals(a, b, StringComparison.OrdinalIgnoreCase)` instead of `a.ToLower() == b.ToLower()` (two allocations plus culture rules). For ASCII data, `System.Text.Ascii` has vectorized `EqualsIgnoreCase`, `ToUpper`\u002F`ToLower` (span to span) and `IsValid`.\n- `Dictionary\u003Cstring, T>` \u002F `HashSet\u003Cstring>` use fast non-randomized hashing only with the default comparer, `StringComparer.Ordinal` or `StringComparer.OrdinalIgnoreCase` (falling back to randomized hashing only on heavy collisions). Any other comparer loses it.\n- Stay in UTF-8 when input and output are UTF-8: search, parse and format `ReadOnlySpan\u003Cbyte>` directly (`u8` literals, `SearchValues\u003Cbyte>`, `TryParse`\u002F`TryFormat` on bytes, `Utf8.TryWrite`) and convert to `string` only when needed.\n- If the app needs no culture data, `\u003CInvariantGlobalization>true\u003C\u002FInvariantGlobalization>` removes the ICU dependency (faster startup, less memory) and makes culture-sensitive string operations ordinal. This changes behavior, so verify the output.\n\n## Contention on shared state\n\nWrites to one shared location from many threads (`Interlocked.Increment` on a global counter, a shared \"total\" field, etc.) serialize all of them on a single cache line, so throughput can get *worse* as cores are added. Split the state, update only the local part, and combine on read. Two options:\n\n**1. Per-core stripes** - index an array by `Thread.GetCurrentProcessorId()` (cheap: cached and periodically refreshed). The id is only a hint: threads migrate, and ids can exceed `ProcessorCount` (hence the modulo), so keep `Interlocked` on the stripe - it's almost always uncontended. Fixed memory and allocation-free reads; works with any number of threads (thread pool, request handlers). Stripes must be padded, see [False sharing](#false-sharing).\n\n```cs\nsealed class StripedCounter\n{\n    private readonly PaddedLong[] _stripes = new PaddedLong[Environment.ProcessorCount];\n\n    public void Increment()\n    {\n        PaddedLong[] stripes = _stripes;\n        Interlocked.Increment(ref stripes[(uint)Thread.GetCurrentProcessorId() % (uint)stripes.Length].Value);\n    }\n\n    \u002F\u002F Not an atomic snapshot, which is fine for statistics.\n    public long Sum()\n    {\n        PaddedLong[] stripes = _stripes;\n        long sum = 0;\n        for (int i = 0; i \u003C stripes.Length; i++)\n            sum += Volatile.Read(ref stripes[i].Value);\n        return sum;\n    }\n}\n```\n\n**2. `ThreadLocal\u003CT>` with `trackAllValues: true`** - each thread updates its own slot with no atomics at all; sum `Values` on read. `Values` allocates a list and includes values of threads that have already exited, and every thread that ever touched it keeps a slot, so this suits a bounded set of long-lived threads (e.g. `Parallel` workers) where writes vastly outnumber reads. Dispose the `ThreadLocal\u003CT>` when done.\n\n```cs\nprivate readonly ThreadLocal\u003Clong> _count = new(trackAllValues: true);\n\nvoid OnItem() => _count.Value++;\nlong Total() => _count.Values.Sum();\n```\n\nIf the work structure allows it, aggregating into plain locals and combining once per task\u002Fpartition (`Parallel.For` with `localInit`\u002F`localFinally`) is cheaper than both.\n\n### False sharing\n\nThreads writing *different* variables still contend if those variables share a cache line (64 bytes on most x64\u002Farm64 CPUs, 128 bytes on Apple M-series): every write invalidates the line in the other cores' caches. The naive striped counter is the classic case:\n\n```cs\n\u002F\u002F 8 longs per 64-byte line: the per-core slots look independent, but cores keep stealing the line from each other.\nlong[] stripes = new long[Environment.ProcessorCount];\nInterlocked.Increment(ref stripes[(uint)Thread.GetCurrentProcessorId() % (uint)stripes.Length]);\n```\n\nFix it by padding each slot so no two hot values can land on the same line:\n\n```cs\nstruct PaddedLong\n{\n    public long Value;\n#pragma warning disable CS0169 \u002F\u002F padding only\n    private InlineArray8\u003Clong> _padding; \u002F\u002F 64 bytes: adjacent Values are 72 bytes apart\n#pragma warning restore CS0169\n}\n```\n\n- Most server hardware (all x64 CPUs and Neoverse-based arm64 CPUs such as Cobalt and Graviton) has 64-byte cache lines, so 64 bytes of padding is usually sufficient. Apple M-series CPUs have 128-byte cache lines, so consider padding to 128 bytes there.\n- The same applies to fields of one object written by different threads (e.g. a ring buffer's head and tail indices): put a padding field between them.\n\n## Safe vectorization (SIMD or SWAR)\n\nIn .NET 11.0 the JIT got improvements in bounds check elimination and now recognizes the following shape for safely loading and processing multiple elements from an array\u002Fspan:\n\n```cs\nwhile (data.Length >= CNS)\n{\n    \u002F\u002F JIT knows that the slice has at least CNS elements, so bounds checks can be elided.\n    \u002F\u002F e.g.:\n    \u002F\u002F  VectorX.Create(data);\n    \u002F\u002F  BitConverter.ToInt32(data);\n    \u002F\u002F  BinaryPrimitives.ReadInt32LittleEndian(data);\n    \u002F\u002F  etc.\n    data = data.Slice(CNS);\n}\n```\n\nFor example, the following C# snippet has no bounds checks in .NET 11.0:\n\n```cs\nint Sum(Span\u003Cint> data)\n{\n    Vector128\u003Cint> sum = default;\n    while (data.Length >= Vector128\u003Cint>.Count)\n    {\n        sum += Vector128.Create(data);\n        data = data.Slice(Vector128\u003Cint>.Count);\n    }\n    int result = Vector128.Sum(sum);\n    foreach (var t in data)\n        result += t;\n    return result;\n}\n```\n\n.NET 12.0 (Preview 1 or main) extends it to more complex loop shapes (e.g. multiple spans):\n\n```cs\nstatic bool Equal(ReadOnlySpan\u003Cushort> a, ReadOnlySpan\u003Cushort> b)\n{\n    if (a.Length != b.Length)\n        return false;\n\n    int i = 0;\n    if (Vector128.IsHardwareAccelerated)\n    {\n        for (; i \u003C= a.Length - Vector128\u003Cushort>.Count; i += Vector128\u003Cushort>.Count)\n        {\n            var va = Vector128.Create(a.Slice(i));\n            var vb = Vector128.Create(b.Slice(i));\n            if (va != vb)\n                return false;\n        }\n    }\n\n    for (; i \u003C a.Length; i++)\n    {\n        if (a[i] != b[i])\n            return false;\n    }\n\n    return true;\n}\n```\n^ has no bounds checks for the main loop in .NET 12.0 (Preview 1).\n\n> [!TIP]\n> This only illustrates the loop shape. For this exact task, just call `a.SequenceEqual(b)`.\n\nMore info about vectorization and SIMD in .NET can be found in the [official documentation](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fstandard\u002Fsimd). Also consider using [TensorPrimitives](https:\u002F\u002Flearn.microsoft.com\u002Fdotnet\u002Fapi\u002Fsystem.numerics.tensors.tensorprimitives).\n\n## Generic specialization via static abstract members\n\nStatic abstract interface members let you specialize a generic method for values supplied by struct tags, without duplicating its source code. The JIT generates separate native versions of `Big\u003CC42>` and `Big\u003CC100>`. In optimized code, it can inline the small `Value` getters and fold expressions and branches that use `T.Value`. This works even when `Big\u003CT>` itself is too large to inline; The tradeoff is increased native code size. `T.Value` is not a C# compile-time constant: constant folding depends on JIT optimizations and getter inlining.\n\n```cs\nusing System.Runtime.CompilerServices;\n\ninterface IConstant {\n    static abstract int Value { get; }\n}\n\nreadonly struct C42 : IConstant {\n    public static int Value => 42;\n}\n\nreadonly struct C100 : IConstant {\n    public static int Value => 100;\n}\n\nstatic class Example\n{\n    static int Big\u003CT>(int x) where T : struct, IConstant\n    {\n        int arg = T.Value;\n\n        \u002F\u002F The large body would go here.\n\n        return arg == 42 ? x * arg : x + arg;\n    }\n\n    static int Use42(int x) => Big\u003CC42>(x);\n    static int Use100(int x) => Big\u003CC100>(x);\n}\n```\n\nIt is also handy for scenarios where you want to leverage different vector sizes or constants in a generic way, allowing the JIT to generate optimized code for each specialization without duplicating the method's source code. Example: summing an array using different vector widths with static abstract members.\n\n```cs\nusing System;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.Intrinsics;\n\nclass Program\n{\n    static void Main()\n    {\n        int[] values = new int[1003];\n\n        if (Vector128.IsHardwareAccelerated)\n            Console.WriteLine(Sum\u003CVector128\u003Cint>, Ops128>(values));\n        if (Vector256.IsHardwareAccelerated)\n            Console.WriteLine(Sum\u003CVector256\u003Cint>, Ops256>(values));\n        if (Vector512.IsHardwareAccelerated) \n            Console.WriteLine(Sum\u003CVector512\u003Cint>, Ops512>(values));\n    }\n\n    [MethodImpl(MethodImplOptions.NoInlining)]\n    static int Sum\u003CV, TOps>(ReadOnlySpan\u003Cint> s)\n        where V : struct\n        where TOps : struct, IOps\u003CV>\n    {\n        V acc = default;\n        int count = TOps.Count;\n\n        while (s.Length >= count)\n        {\n            acc = TOps.Add(acc, TOps.Load(s));\n            s = s.Slice(count);\n        }\n\n        int sum = TOps.Sum(acc);\n        foreach (int x in s) sum = unchecked(sum + x);\n        return sum;\n    }\n}\n\n\ninterface IOps\u003CV> where V : struct\n{\n    static abstract int Count { get; }\n    static abstract V Load(ReadOnlySpan\u003Cint> s);\n    static abstract V Add(V a, V b);\n    static abstract int Sum(V v);\n}\n\nreadonly struct Ops128 : IOps\u003CVector128\u003Cint>>\n{\n    public static int Count => Vector128\u003Cint>.Count;\n    public static Vector128\u003Cint> Load(ReadOnlySpan\u003Cint> s) => Vector128.Create(s);\n    public static Vector128\u003Cint> Add(Vector128\u003Cint> a, Vector128\u003Cint> b) => a + b;\n    public static int Sum(Vector128\u003Cint> v) => Vector128.Sum(v);\n}\n\nreadonly struct Ops256 : IOps\u003CVector256\u003Cint>>\n{\n    public static int Count => Vector256\u003Cint>.Count;\n    public static Vector256\u003Cint> Load(ReadOnlySpan\u003Cint> s) => Vector256.Create(s);\n    public static Vector256\u003Cint> Add(Vector256\u003Cint> a, Vector256\u003Cint> b) => a + b;\n    public static int Sum(Vector256\u003Cint> v) => Vector256.Sum(v);\n}\n\nreadonly struct Ops512 : IOps\u003CVector512\u003Cint>>\n{\n    public static int Count => Vector512\u003Cint>.Count;\n    public static Vector512\u003Cint> Load(ReadOnlySpan\u003Cint> s) => Vector512.Create(s);\n    public static Vector512\u003Cint> Add(Vector512\u003Cint> a, Vector512\u003Cint> b) => a + b;\n    public static int Sum(Vector512\u003Cint> v) => Vector512.Sum(v);\n}\n```\n\n# ASP.NET Core\n\nCode-level advice for HTTP throughput benchmarks.\n\n- Start from `WebApplication.CreateSlimBuilder(args)` (or `CreateEmptyBuilder` + `builder.WebHost.UseKestrelCore()`) and add only what's needed. Every middleware component (HTTPS redirection, auth, CORS, response compression, static files, developer exception page) costs something per request.\n- Logging: without an `appsettings.json` that raises `Microsoft.AspNetCore` to `Warning`, the default level is `Information` and the host logs every request to the console - a massive bottleneck. Call `builder.Logging.ClearProviders()` or raise the level.\n- JSON: register source-generated metadata with `builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));`. For hand-written responses, serialize with a reused `Utf8JsonWriter` (`writer.Reset(response.BodyWriter)`) instead of allocating one per request.\n\n# Magic knobs to Tune .NET Performance\n\n> [!WARNING]\n> It is highly recommended to keep the default settings unless you have measured and understood the performance implications of changing them. \n\nMost of these knobs are relevant only for server workloads or performance-critical scenarios. They're not applicable for general-purpose libraries.\n\n⭐ - known to have a visible impact on performance (typically, in synthetic benchmarks).\n\n| Environment variable (CoreCLR Release, .NET 10.0+) | Default | Values to try | Purpose and trade-offs |\n| --- | --- | --- | --- |\n| ⭐`DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS` | `0` | `1` | Run I\u002FO continuations directly on poller threads instead of dispatching them to workers - beneficial for workloads with many small requests. ⚠️ Blocking or lengthy continuations can stall I\u002FO ⚠️ |\n| ⭐`DOTNET_ThreadPool_UnfairSemaphoreSpinLimit` | `70` in .NET 10.0; `1024` in current .NET 11.0 | `0`, `0x400`, `0xC00` | Trade worker wake latency against CPU spent spinning. `0` might be useful as a mitigation for high CPU usage (especially on arm64) at the cost of throughput. Large values might improve synthetic benchmark performance. |\n| ⭐`DOTNET_GCDynamicAdaptationMode` | `1` | `0` | Disable DATAS for server GC. Can improve throughput at the expense of memory; compare against tuning DATAS (e.g. `DOTNET_GCDGen0GrowthPercent`) rather than disabling it. |\n| ⭐`DOTNET_HillClimbing_Disable` | `0` | `1` | Disable ThreadPool hill climbing (improves time to steady state). |\n| `DOTNET_SYSTEM_NET_SOCKETS_THREAD_COUNT` | Automatic; processor count when inline completions are enabled | `1`, `2`, `4`, `8`, up to processor count | Tune I\u002FO poller count. Fewer pollers can reduce scheduling and cache overhead; too few can serialize processing. Values are decimal. |\n| `DOTNET_gcServer` | varies by environment | `1` | Typically enabled by default for server workloads. Might improve the performance of desktop\u002Fconsole tools. |\n| `DOTNET_GCDTargetTCP` | Effective target `2%` (configuration `0`) | `1` | Lower DATAS's target throughput-cost percentage. Encourages more heaps when GC cost exceeds the target. Only relevant with DATAS enabled. |\n| `DOTNET_GCDGen0GrowthPercent` | Effective multiplier `100%` (configuration `0`) | `0xC8` | Scale DATAS's gen0 budget multiplier to 200% of its default. Trades memory for potentially fewer collections. Only relevant with DATAS enabled. |\n| `DOTNET_TC_CallCountingDelayMs` | `100` ms; longer on a single processor | `0` | Only for short-lived console tools where JIT warmup takes too long: remove the tiering delay while retaining the normal call-count threshold. Can increase compilation work early in execution. |\n| `DOTNET_TieredCompilation` | `1` | `0` | Alternative for short-lived console tools where JIT warmup takes too long: disable tiering and JIT optimized code on first use. Removes tiered warmup but disables dynamic PGO and can increase initial JIT cost. |\n\nUsing NativeAOT or disabling tiered compilation via `DOTNET_TC_CallCountingDelayMs=0`\u002F`DOTNET_TieredPGO=0`\u002F`DOTNET_TieredCompilation=0` may significantly improve performance for short-lived console tools or benchmarks that measure the entire process rather than just steady-state execution.\n\n# NativeAOT-specific tuning\n\nRecommended reading: Microsoft's [Optimizing AOT deployments](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fdotnet\u002Fcore\u002Fdeploying\u002Fnative-aot\u002Foptimizing) article, plus the runtime's [CPU instruction-set tuning guide](https:\u002F\u002Fgithub.com\u002Fdotnet\u002Fruntime\u002Fblob\u002F9da219572c1\u002Fsrc\u002Fcoreclr\u002Fnativeaot\u002Fdocs\u002Foptimizing.md). The latter describes implementation-specific options that can change between SDK versions.\n\n> [!NOTE]\n> These are publish-time MSBuild properties: republish for each experiment. NativeAOT has no JIT or tiered compilation, so the CoreCLR JIT\u002Ftiering environment variables above do not apply.\n\n| MSBuild setting | Purpose and trade-offs |\n| --- | --- |\n| `-p:OptimizationPreference=Speed` | Optimize for execution time (`--Ot`) instead of the default size\u002Fspeed balance. A good throughput experiment, but can increase executable size and instruction-cache pressure. |\n| `-p:OptimizationPreference=Size` | Optimize for executable size (`--Os`). Useful when distribution size or memory footprint matters more than peak throughput; measure the speed trade-off. |\n| `-p:IlcInstructionSet=native` | Target instruction sets supported by the build machine's CPU. Useful for local benchmarks or homogeneous deployments; no cross-architecture compilation support, and the executable may not run on older CPUs. Use an explicit instruction-set baseline for heterogeneous deployments. |\n| `-p:IlcInstructionSet=armv8.1-a` | If `IlcInstructionSet=native` is not acceptable for you, consider explicitly raising the baseline from ARMv8.0-A to ARMv8.1-A to include LSE (crucial for atomics-heavy workloads). |\n\n```sh\ndotnet publish -c Release -r linux-arm64 -p:PublishAot=true -p:OptimizationPreference=Speed -p:IlcInstructionSet=native\n```\n\n# General notes\n\n- Consider filing a [dotnet\u002Fruntime](https:\u002F\u002Fgithub.com\u002Fdotnet\u002Fruntime\u002Fissues) issue only for a clear, reproducible missed optimization in the JIT or libraries with meaningful measured impact. Check for duplicates, include a minimal repro and measurements, and obtain the user's approval before filing.\n- Compare equivalent execution plans before blaming the language. Consider pairwise comparisons, stronger filtering, and verification requirements before tuning code generation.\n- Don't draw conclusions about workloads from tiny synthetic benchmark results.",{"name":5,"description":7},"master","b30b1c1908dbc56a8184128f18803053d762ccb5","codex\u002Fdeniz-dotnet-general\u002Fskills\u002Fblazing-fast-dotnet",0,"https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins","https:\u002F\u002Fgithub.com\u002FBlind-Striker","denizirgin.com","VP of Engineering - \r\n@armutcom @homeruntech @prontopro\r\n |  Speaker \r\n@CodeFiction\r\n, http:\u002F\u002Fcodefiction.tech | Developer, gamer, blogger, maiden iron fan","2026-11-13 00:23:18",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill blazing-fast-dotnet",{"tool":40,"command":41},"bunx","bunx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill blazing-fast-dotnet",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Blind-Striker\u002Fagent-skills-and-plugins --skill blazing-fast-dotnet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fcodex\u002Fdeniz-dotnet-general\u002Fskills\u002Fblazing-fast-dotnet\u002FSKILL.md",true,[48],{"path":49,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":16},"LICENSE","许可证",1063,[53,60,67,74,81,88],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":20},"01M79YGWBJ52PHMSTKJ3RJ3AWR","writing-tunit-tests","Write tests in TUnit — the attributes, the async assertion model, data-driven cases, lifecycle hooks, and the parallelism rules. USE FOR writing or fixing a test in a TUnit project, translating a test idea into TUnit syntax, or reviewing TUnit test code for API mistakes. DO NOT USE FOR deciding what to test, judging whether a test is any good, or running tests.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fwriting-tunit-tests\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":20},"01M79YGR3Y9RCRS6TD71D0KKP8","dotnet-walls","Walls for a .NET change in a repository without its own quality gates — pinned, ephemeral analyzer, format, clone and scanner commands for the verify step, their identity ratchet, and the build traps. Use during a walls preflight, or when a worker's verify step needs .NET quality gates.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fdotnet-walls\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":20},"01M79YGFNJBST7D803NQW3SBYM","csharp-15","Write, review and modernize C# 15 (.NET 11) code correctly. Covers every C# 15 feature - collection expression arguments (`[with(...), ...]`), union types (`union`, `[Union]`, `IUnion`, custom unions), closed class hierarchies (`closed`), extension indexers, labeled `break`\u002F`continue`, non-virtual static interface members on runtimes without default interface methods, and the preview memory-safety model (`unsafe(expr)`, `safe`, requires-unsafe members). Use when code targets net11.0 or LangVersion 15\u002Fpreview, when the user mentions any of these features, when replacing marker interfaces, OneOf-style results, `goto`\u002Fflag loop exits or capacity\u002Fcomparer boilerplate, or when the build reports CS8121, CS8509, CS8655, CS8510, CS0121\u002FCS0411 on a `with(...)` element, CS9370, CS9380 or CS9363.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-dotnet-general\u002Fcsharp-15\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":20},"01M79YGAV031473HSX6FN87ENH","verified-waves","Run one task as verified multi-agent waves. Plans the fan-out, sends findings to fresh skeptics, keeps a ledger, and reports N of M done; small tasks stay solo.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fverified-waves\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":20},"01M79YG6QXNND4WRPP3GATSY8J","harness","The bundled dispatch harness, which runs a task file on worker models through OpenCode or Codex, fences their writes, escalates their asks to the operator, settles each result from git and its verify commands, and records every step in a ledger. Its commands, task file, modes and write fence, configuration, runs and their recovery, ledger and exit codes.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fharness\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":20},"01M79YG2P5S91SDTA5912XJ4FV","delegating-to-worker-models","Use when you hand off implementation, a plan, research a decision will rely on, or a review, and you brief the worker and check what comes back. A subagent that searches, reads in parallel, or keeps your context small is ordinary tool use. Covers what stays with you, the mechanism, assigning work by strength, the walls preflight, prompts without contradictions, the worker contract and model profiles, evidence from your own run, review, and the fix-up loop.","https:\u002F\u002Fgithub.com\u002FBlind-Striker\u002Fagent-skills-and-plugins\u002Fblob\u002Fmaster\u002Fskills\u002Fdeniz-coordination\u002Fdelegating-to-worker-models\u002FSKILL.md",[],[]]