Performance rules

Allocations, enumeration, and hot-path work.

Rules

RuleTitleCode fix
E128009Use MinBy/MaxBy instead of OrderBy().First()Yes
E128010Pass HttpCompletionOption.ResponseHeadersRead to HttpClient callsYes
E128015Use string interpolation instead of string.FormatYes
E128018Use ToArray() instead of ToList() for read-only foreachYes
E128026Redundant HashSet allocation in FrozenSet creationYes
E128027Use FrozenSet/FrozenDictionary for static readonly collectionsYes
E128029Replace multi-string OR-chain with HashSet.ContainsYes
E128066Linear lookup inside loop creates O(n²) complexityYes
E128067String concatenation in loop creates O(n²) allocationsYes
E128068Sort operation inside loop creates O(n² log n) complexityYes
E128069List.Insert(0, ...) in loop creates O(n²) complexityNo
E128072Prefer SHA256.HashData() over SHA256.Create() (default: Info)Yes
E128081Use StringBuilderPool instead of new StringBuilder() (default: Info)Yes
E128083Use ImmutableCollectionsMarshal.AsImmutableArray instead of ImmutableArray.Create/CreateRange with ToArrayYes
E128084Use CollectionsMarshal.AsSpan instead of List.GetRange or a list indexer loopYes
E128085Use foreach + AddRange instead of SelectMany.ToListYes
E128098Collapse chained or looped string.Replace calls into a single passYes
E128102Use SearchValues<char> for IndexOfAny scansYes
E128106Index a collection with a bound taken from a different collectionNo
E128116Do not use MethodImplOptions.AggressiveOptimizationYes
E128117Use LibraryImport instead of DllImportYes
E128121Use SequenceEqual instead of an element-by-element loopYes
E128122Guard an expensive log argument with IsEnabledYes
E128123Use [GeneratedRegex] for a constant patternYes
E128124Cache SearchValues in a static readonly fieldYes
E128131Parse UTF-8 bytes with the span overload instead of a decoded stringYes
E128132Do not use a culture-aware comparer for a collection keyYes
E128133Use an alternate lookup instead of a temporary string keyYes
E128134Use BitOperations.PopCount instead of a shift loopYes
E128135Use TensorPrimitives instead of a sum, min, or max loopYes
E128140Use Span.Fill/Clear/CopyTo instead of an element loopYes
E128141Use a u8 literal instead of Encoding.UTF8.GetBytesYes
E128152Complexity past the e128_max_complexity ceiling (nested loops, recursion)Yes
E128153List.RemoveAt(0) in loop creates O(n²) complexityNo
E128180Entity Framework Core query executed inside a loopNo
E128185Entity Framework Core SaveChanges inside a loopNo
E128187Parallel.ForEachAsync without a degree cap (default: Info)No
E128203HTTP request inside a loop creates N+1 round tripsNo
E128204Database command inside a loop runs one round trip per iterationNo
E128205Collection filled in a loop has a known final countYes
E128206Empty loop body spins the CPUNo
E128207Reflection lookup inside a loopYes
E128208ContainsKey then indexer on a ConcurrentDictionaryYes
E128209GetBytes(...).Length inside a loop allocates a byte array for its lengthYes
E128210new Regex inside a loop with a loop-invariant patternYes
E128211Task.Delay in a loop has no cancellation tokenNo
E128212ToCharArray result used only for indexing or iterationYes
E128213Activator.CreateInstance inside a loopNo
E128214HTTP handler does not enable automatic decompressionNo
E128215StringBuilder created without capacity for a known append countYes
E128216Unbounded channel can grow without limitNo
E128217Large struct passed by valueNo
E128223Hand-rolled child-process capture (use Process.RunAndCaptureText)No
E128224Read-only MemoryStream over a string or byte arrayNo
E128226Comparer set built by constructor and Add loopYes
E128271MemoryStream round trip copies a byte array (default: Info)No
E128229Middleware binds the Func<Task> next delegateYes
E128230Static files served through the runtime pipelineNo
E128231string.Split result enumerated without a stored arrayYes
E128233Parallel.For runs one delegate per itemYes
E128235Readonly field re-read inside a loopYes
E128247A readonly field copies its mutable struct on every callNo
E128249Array.Resize or Concat regrows an array inside a loopNo
E128253Struct dictionary or set key without IEquatable<T>No
E128255Use TensorPrimitives.Add/Multiply instead of an element-wise loopYes

Rule details

E128009: OrderBy + First

Flags OrderBy(...).First() and OrderByDescending(...).First() patterns. MinBy/MaxBy run in O(n) instead of O(n log n).

// Before (warns)
var cheapest = products.OrderBy(p => p.Price).First();

// After
var cheapest = products.MinBy(p => p.Price);

E128010: HttpClient response buffering

Flags GetAsync, PostAsync, SendAsync, etc. called without HttpCompletionOption.ResponseHeadersRead. Without it, the entire response body is buffered into memory before control returns.

// Before (warns)
var response = await client.GetAsync("/large-file");

// After
var response = await client.GetAsync("/large-file", HttpCompletionOption.ResponseHeadersRead);

E128015: String interpolation over string.Format

Flags string.Format(...) calls that can be replaced with string interpolation ($"..."). Interpolation is faster (avoids boxing and parsing) and more readable.

// Before (warns)
var msg = string.Format("Hello, {0}!", name);

// After
var msg = $"Hello, {name}!";

E128018: ToList in foreach

Flags ToList() calls used only as the source of a foreach loop. ToArray() allocates less memory for read-only iteration.

// Before (warns)
foreach (var item in items.ToList()) { }

// After
foreach (var item in items.ToArray()) { }

E128026: Redundant HashSet in FrozenSet

Flags new HashSet<T>(...).ToFrozenSet() — the intermediate HashSet allocation is unnecessary. Pass the collection directly to ToFrozenSet().

// Before (warns)
var set = new HashSet<string>(items).ToFrozenSet();

// After
var set = items.ToFrozenSet();

E128027: Static readonly frozen collections

Flags static readonly HashSet<T> and static readonly Dictionary<TKey, TValue> fields initialized at declaration. Frozen collections trade construction time for optimized read access — ideal for process-lifetime fields. Requires .NET 8+.

// Before (warns)
private static readonly HashSet<string> AllowedMethods = new(StringComparer.Ordinal) { "GET", "POST" };

// After
private static readonly FrozenSet<string> AllowedMethods = new HashSet<string>(StringComparer.Ordinal) { "GET", "POST" }.ToFrozenSet();

E128029: Multi-string OR-chain

Flags 3+ ||-chained string equality tests on the same operand. Replace with HashSet<string>.Contains() for cleaner code and O(1) lookup.

// Before (warns)
if (method == "GET" || method == "POST" || method == "PUT") { }

// After
private static readonly FrozenSet<string> AllowedMethods = ...;
if (AllowedMethods.Contains(method)) { }

E128066: Linear lookup in loop (O(n²))

Flags linear-time methods (.Contains, .Any, .IndexOf, .Remove, .Exists, .Find, .FindAll, .FindIndex) called on list/array/IEnumerable<T> types inside loops or LINQ lambdas. Also detects .Where(...).Count() chains. Excludes O(1) types (HashSet<T>, Dictionary<K,V>, FrozenSet<T>, etc.), an IQueryable<T> receiver that E128180 owns, and constant-bound for loops.

// Before (warns)
foreach (var item in items)
    if (lookup.Contains(item)) { }

// After
var lookupSet = lookup.ToHashSet();
foreach (var item in items)
    if (lookupSet.Contains(item)) { }

Code fix converts receiver to HashSet<T> via .ToHashSet() (offered for .Contains and .Any only).

E128067: String concatenation in loop

Flags string += inside loops. Each iteration allocates a new string, creating O(n²) total allocations. Use StringBuilder instead.

// Before (warns)
foreach (var line in lines)
    result += line;

// After
var sb = new StringBuilder();
foreach (var line in lines)
    sb.Append(line);
var result = sb.ToString();

E128068: Sort operation inside loop

Flags .Sort() (List<T>, Array), .OrderBy(), .OrderByDescending(), .ThenBy(), .ThenByDescending() (System.Linq.Enumerable) inside loops. Sorting per iteration is O(n² log n) overall. Sort once before the loop or use a sorted collection.

// Before (warns)
foreach (var batch in batches)
    items.Sort();

// After
items.Sort();
foreach (var batch in batches) { }

The code fix moves the sort statement before the loop. It applies to a statement-position Sort() on a List<T> or array. The receiver and every sort argument must stay invariant across iterations. The loop body must never mutate the receiver, call a method on it, pass it as an argument, or alias it. The fix declines a LINQ sort, a sort inside an if, an unbraced loop body, and a receiver or argument that reads the loop variable.

E128069: List.Insert(0, ...) in loop

Flags list.Insert(0, ...) inside loops. Each insert at index 0 shifts all existing elements, making the loop O(n²). Use LinkedList<T>.AddFirst or collect and reverse.

// Before (warns)
foreach (var item in source)
    result.Insert(0, item);

// After
var result = source.Reverse().ToList();

E128072: SHA256.Create() obsolete pattern (Info)

Flags SHA256.Create() followed by .ComputeHash(). The static SHA256.HashData() method introduced in .NET 5 performs the same operation without allocating a disposable object.

// Before (info)
using var sha = SHA256.Create();
var hash = sha.ComputeHash(data);

// After
var hash = SHA256.HashData(data);

E128081: Use StringBuilderPool instead of new StringBuilder()

Flags every new StringBuilder() and every target-typed new() that produces a System.Text.StringBuilder. The rule runs only when the compilation references Pug.Core.Text.StringBuilderPool. Code inside the StringBuilderPool class is exempt. The rule reports at info. A code fix rewrites the creation to the pooled form.

// Before (info)
var builder = new StringBuilder();

// After
var builder = StringBuilderPool.Shared.Rent();

E128083: ImmutableArray.Create with ToArray copies the array

Flags ImmutableArray.Create(x.ToArray()) and ImmutableArray.CreateRange(x.ToArray()). Both patterns copy the array unnecessarily. ImmutableCollectionsMarshal.AsImmutableArray wraps an existing array in zero copies. The rule fires only when ToArray comes from an allowlisted BCL type (Enumerable, List<T>, HashSet<T>, Queue<T>, Stack<T>). A user-defined ToArray may return a shared array.

// Before (warns)
var result = ImmutableArray.Create(items.ToArray());

// After
var result = ImmutableCollectionsMarshal.AsImmutableArray(items.ToArray());

E128084: List copies and indexer loops

Flags two List<T> shapes.

Flags list.GetRange(start, count). GetRange allocates an intermediate List<T>. Use CollectionsMarshal.AsSpan(list).Slice(start, count).ToArray() to copy directly from the internal array without the intermediate allocation. The rule fires only when flow analysis proves the receiver non-null, because AsSpan(null) returns an empty span where GetRange throws. A bad range throws ArgumentOutOfRangeException from Slice.

Flags for (int i = 0; i < list.Count; i++) when the body only reads list[i]. The indexer repeats the bounds check on every element. The rule stays silent when the loop calls any other member on the list, writes through the indexer, or uses the loop variable for another purpose. The loop-variable rewrite enumerates CollectionsMarshal.AsSpan(list), which keeps the old buffer after a resize. The rule therefore stays silent when the body can run other code that may resize the list: a direct mutation, an await or yield, a delegate call, a call into source code or to an overridable member, or a property accessor with a body. A body that calls only non-overridable framework members and reads auto-properties still reports.

// Before (warns)
var slice = list.GetRange(2, 5);

for (int i = 0; i < list.Count; i++)
{
    total += list[i].Length;
}

// After
var slice = CollectionsMarshal.AsSpan(list).Slice(2, 5).ToArray();

foreach (var item in CollectionsMarshal.AsSpan(list))
{
    total += item.Length;
}

E128085: SelectMany.ToList creates LINQ iterator allocations

Flags .SelectMany(lambda).ToList(). This pattern creates intermediate LINQ iterator allocations and grows the result list without known capacity. A foreach loop with AddRange avoids both.

// Before (warns)
var result = groups.SelectMany(g => g.Items).ToList();

// After
var result = new List<Item>();
foreach (var g in groups)
    result.AddRange(g.Items);

E128098: Collapse chained or looped string Replace calls into a single pass

Flags two or more chained string.Replace calls at the outermost call. Also flags a while loop whose condition calls Contains on a string and whose body assigns s = s.Replace(...) to that string. Each call allocates a new string and copies the whole value.

// Before (warns)
var cleaned = input.Replace("a", "").Replace("b", "");

// After
var builder = new StringBuilder(input.Length);
foreach (var c in input)
{
    if (c is not ('a' or 'b'))
    {
        builder.Append(c);
    }
}
var cleaned = builder.ToString();

E128102: Use SearchValues<char> for IndexOfAny scans

Flags string.IndexOfAny and string.LastIndexOfAny. These scan char by char without SIMD. Use a cached SearchValues<char> with the span IndexOfAny overload, which scans 16 to 32 bytes per instruction on AVX2, AVX-512, and ARM Neon.

// Before (warns)
var i = path.IndexOfAny(new[] { '/', '\\' });

// After
private static readonly SearchValues<char> PathChars = SearchValues.Create("/\\");

var i = path.AsSpan().IndexOfAny(PathChars);

The code fix hoists a SearchValues<char> field into the containing type and rewrites the call to the span overload. The span overload keeps the int index semantics. It offers no fix when the argument is not a char array with literal elements.

E128106: Index a collection with a bound taken from a different collection

Flags an element access whose index comes from an Enumerable.Range(0, other.Count) lambda parameter, or from a for loop whose condition reads other.Count or other.Length, when the indexed collection is a different symbol. A relational comparison against the indexed collection’s own Count or Length in the same scope suppresses the report. A ragged pair throws IndexOutOfRangeException on the first short collection. No code fix.

// Before (warns)
var cells = Enumerable.Range(0, columns.Count).Select(i => rows[i]).ToList();

// After
var cells = Enumerable.Range(0, columns.Count)
    .Select(i => i < rows.Count ? rows[i] : default)
    .ToList();

E128116: Do not use MethodImplOptions.AggressiveOptimization

Flags [MethodImpl(MethodImplOptions.AggressiveOptimization)]. The flag disables tiered compilation for the method. The code fix removes the flag and keeps the other flags. When AggressiveOptimization is the only flag, the fix removes the attribute and keeps the doc comment.

E128117: Use LibraryImport instead of DllImport

Flags every [DllImport] on a method when the target defines LibraryImportAttribute. LibraryImport generates the marshalling code at compile time. The code fix applies only when every parameter and the return type are blittable, AllowUnsafeBlocks is on, and the attribute uses only EntryPoint and SetLastError. The fix renames the attribute, drops extern, and makes the method and the containing types partial.

E128121: Use SequenceEqual instead of an element-by-element loop

Flags a for loop that compares two arrays element by element and returns false on the first mismatch. The rule applies only when these conditions hold:

  • An earlier if returns false when the two Length values differ.
  • The loop bound is the Length of one of the two arrays.
  • The element type is an integral type, bool, char, or an enum. A floating-point type is excluded because NaN compares differently.

The code fix rewrites the loop to return left.AsSpan().SequenceEqual(right);.

E128122: Guard an expensive log argument with IsEnabled

Flags Log* calls where an argument is a non-constant interpolated string or a non-constant string concatenation. The rule stays silent when an IsEnabled check for the same logger and level wraps the call or returns early. The check can sit in a local variable, or in a helper method or property that returns it. The message is built before the level check. The code fix wraps the statement in if (logger.IsEnabled(LogLevel.X)). The fix applies only to a statement in a block, and only when the logger expression contains no call.

E128123: Use GeneratedRegex for a constant pattern

Flags a static readonly Regex field built from a string literal when the target defines GeneratedRegexAttribute and the language version is C# 13 or later. [GeneratedRegex] builds the matcher at compile time and keeps the pattern in source. The code fix applies only when the arguments are constants and the options are a plain list of flags. It replaces the field with a partial property and makes every containing type partial. The fix adds matchTimeoutMilliseconds: Timeout.Infinite, which keeps the original behavior and satisfies E128011. It drops RegexOptions.Compiled.

E128124: Cache SearchValues in a static readonly field

Flags SearchValues.Create outside a static readonly field or a static property initializer. The rule applies only when every argument is a constant or a static readonly value. The call builds an immutable table on every call. The code fix hoists the call into a private static readonly field named after the method, for example _containsDelimiterSearchValues.

E128131: Parse UTF-8 bytes without a decoded string

Flags Encoding.UTF8.GetString(...) passed to a Parse or TryParse call. The decode allocates a string that the parse then reads through a span. The span overload reads the bytes directly.

The fix replaces the decoded argument with the byte argument. When the method needs an IFormatProvider, the fix appends CultureInfo.CurrentCulture.

// Before
int value = int.Parse(Encoding.UTF8.GetString(bytes));

// After
int value = int.Parse(bytes, CultureInfo.CurrentCulture);

E128132: Do not use a culture-aware comparer for a collection key

Flags StringComparer.CurrentCulture, CurrentCultureIgnoreCase, InvariantCulture, and InvariantCultureIgnoreCase in the constructor of Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, SortedDictionary<TKey, TValue>, HashSet<T>, or SortedSet<T>. A culture-aware comparer holds a CompareInfo reference and compares code points with culture rules.

The fix replaces the comparer with Ordinal or OrdinalIgnoreCase.

E128133: Use an alternate lookup instead of a temporary string key

Flags a lookup key of the form new string(span) on a string-keyed Dictionary<TKey, TValue>, ConcurrentDictionary<TKey, TValue>, or HashSet<T>. The construction allocates a string on every lookup.

The fix uses GetAlternateLookup<ReadOnlySpan<char>>(), which compares the span in place. The analyzer reports only when the comparer is default or ordinal. Culture-aware comparers throw with alternate lookup.

The receiver must be a readonly field without constructor writes, or an unchanged local. A local is unchanged when no assignment, deconstruction, ref or out argument, writable ref alias, or address escape writes to it. A collection expression with a with(...) element must pass one ordinal comparer.

The code fix does not offer Fix All. One file can mix comparer kinds.

E128134: Use BitOperations.PopCount instead of a shift loop

Flags a while (value != 0) loop whose body is exactly count += value & 1; and value >>= 1;. The loop counts one bit per iteration. BitOperations.PopCount compiles to one hardware instruction.

The fix replaces the loop with count += BitOperations.PopCount(value); and casts a signed value to its unsigned width.

The analyzer skips a loop whose counter is unsigned (uint or ulong) by design. The counter must be int or long. The test Silent_WhenTheCountIsUnsigned pins this behavior.

E128135: Use TensorPrimitives.Sum instead of a sum loop

Flags a foreach loop whose body reduces the elements of a float or double source one at a time, where the source is an array, Span<T>, or ReadOnlySpan<T>.

A sum loop adds the element. A maximum loop reads if (value > max) { max = value; }, and a minimum loop reads if (value < min) { min = value; }. The min and max shapes report only when the accumulator starts at the neutral value: MinValue for a maximum and MaxValue for a minimum. Any other start value would survive the reduction.

The fix replaces the loop with sum += TensorPrimitives.Sum(source); or with TensorPrimitives.Max/Min(source) in the accumulator declaration. The analyzer reports only when the referenced System.Numerics.Tensors assembly declares every matching member.

E128140: Use a span bulk method instead of an element loop

Flags a for loop that writes one element per iteration, in these shapes:

  • target[i] = value becomes Fill(value).
  • target[i] = 0, false, null, or default becomes Clear().
  • target[i] = source[i] becomes source.CopyTo(target).

The loop must count from zero with i++ and stop at < target.Length. The receiver must be a name, not a method call. For the copy shape the loop bound belongs to the source, because CopyTo reads the whole source span.

// Before (warns)
for (var i = 0; i < values.Length; i++)
{
    values[i] = 1;
}

// After
values.AsSpan().Fill(1);

The code fix calls AsSpan() on an array and calls the method directly on a Span<T>.

E128141: Use a u8 literal instead of Encoding.UTF8.GetBytes

Flags Encoding.UTF8.GetBytes with a literal string argument. The call runs the UTF-8 encoder on every call. A u8 literal stores the bytes in the assembly.

// Before (warns)
byte[] bytes = Encoding.UTF8.GetBytes("abc");

// After
byte[] bytes = "abc"u8.ToArray();

The rule needs C# 11 or later. The fix emits the bare literal when the target is a ReadOnlySpan<byte>. Every other target, including Span<byte>, keeps the byte[] shape through ToArray().

E128152: Complexity ceiling: nested loops and non-memoized recursion

Flags two shapes whose cost grows past the configured ceiling. Loop depth counts only loops whose trip count varies. A loop bounded by a constant, an array created with a constant length, or a constant collection expression does not raise the tier. A coordinate step adds no depth either: when an inner loop’s trip count reads an element the enclosing loop produced, such as a cell inside a row, the enclosing loop does not count, because the pair costs one visit per element rather than one per pair. Two varying loops infer quadratic, three infer cubic, and four or more infer cubic or worse. A method that calls itself two or more times and passes a parameter made smaller by a constant step infers exponential. Recursion that halves its argument, such as binary search, stays silent. Recursion counts as memoized only when the body both reads and writes the same field or IDictionary-typed local. Reach is direct same-type recursion only. A single self-call such as tree or tail recursion stays silent, and a single loop stays silent. The diagnostic anchors on the inner loop or on the recursive method declaration.

Two code actions serve this rule. Suppress with a justification comment wraps the reported loop, or the reported recursive method, in a #pragma warning disable and #pragma warning restore pair. The disable line carries // Justification: state why this site is output-bound, which E128047 accepts. Replace that sentence with the reason. Replace the nested scan with a set lookup rewrites a two-deep equality scan as a HashSet lookup. The second action appears only when the outer loop is top level, the inner body is one == guard that returns on a match, the inner comparison side is exactly the iteration variable, and the method never mentions the inner collection anywhere else.

Set the allowed ceiling with e128_max_complexity in .globalconfig or .editorconfig. Named tiers: linear, linearithmic, quadratic, cubic, exponential. Default linear, so linearithmic and worse fires. In-loop lookups, sorts, insertions, and string concatenation keep their dedicated rules (E128066, E128067, E128068, E128069, E128153) and stay out of this rule. At ceiling exponential neither shape can fire.

// Before (warns)
foreach (var a in items)
{
    foreach (var b in items)
    {
        _ = a.Length + b.Length;
    }
}

// After — hoist the outer work, or track the inner iteration on a set
var seen = new HashSet<string>(items);
foreach (var a in items)
{
    Process(a);
}

E128153: List.RemoveAt(0) in loop creates O(n²) complexity

E128180: Entity Framework Core query executed inside a loop

Flags an Entity Framework Core query that executes inside a for, foreach, while, or do body. Each iteration runs one database round trip, which is the N+1 query problem. The rule reads the materializing calls, such as ToList, FirstOrDefaultAsync, CountAsync, Find, Contains, Last, Average, and ExecuteDelete. It also covers AsEnumerable or AsAsyncEnumerable that feeds a nested foreach, and a query syntax expression (from ... select) that a materializing call consumes. A foreach with a deconstruction pattern counts as a loop. E128066 defers every IQueryable receiver to this rule. The receiver must be a DbSet<T>, an EF queryable, or an IQueryable<T> chain rooted in an EF type. The foreach source expression and the for initializer run once, so neither counts as a loop body. The whole rule stays off when EF Core is absent from the compilation. No code fix.

// Before (warns)
foreach (var id in ids)
{
    var row = await db.Rows.FirstOrDefaultAsync(r => r.Id == id);
}

// After
var rows = await db.Rows.Where(r => ids.Contains(r.Id)).ToListAsync();

E128185: Entity Framework Core SaveChanges inside a loop

Flags a SaveChanges or SaveChangesAsync call on an Entity Framework Core context inside a for, foreach, while, or do body. Each iteration costs one database round trip per row. A call in a foreach source expression or a for initializer is skipped, because it runs once. A DbContext type from another namespace is skipped. The rule stays off when EF Core is absent from the compilation. No code fix.

// Before (warns)
foreach (var row in rows)
{
    context.Rows.Add(row);
    context.SaveChanges();
}

// After
foreach (var row in rows)
{
    context.Rows.Add(row);
}

context.SaveChanges();

E128187: Parallel.ForEachAsync without a degree cap

Flags a Parallel.ForEachAsync call that passes no ParallelOptions argument, or an inline new ParallelOptions initializer that sets no MaxDegreeOfParallelism member. The call then runs at most Environment.ProcessorCount operations at once, which is the default cap. An I/O-bound body can need a different cap, so the rule reports at Info severity. A MaxDegreeOfParallelism assignment of any expression silences the rule, including -1 and a computed value. Options held in a variable, a parameter, a field, or a factory call are not reported. A user type named Parallel is not reported. No code fix.

// Before (warns)
await Parallel.ForEachAsync(urls, async (url, ct) => await FetchAsync(url, ct));

// After
await Parallel.ForEachAsync(
    urls,
    new ParallelOptions { MaxDegreeOfParallelism = 8 },
    async (url, ct) => await FetchAsync(url, ct));

E128203: HTTP request inside a loop

Flags an HttpClient request call inside a loop body. Each iteration pays a network round trip, which is the N+1 request shape. The rule does not require an await, because the round trip is paid either way.

The rule reads SendAsync, GetAsync, PostAsync, PutAsync, DeleteAsync, and PatchAsync. The receiver must derive from HttpClient.

Exclusions:

  • A for loop with a compile-time constant bound.
  • A request in a loop header, which runs once.
  • A loop body that calls Task.Delay or Thread.Sleep, which marks a retry or poll loop.
  • A lambda or local function body.

No code fix. The batch contract is application policy.

E128204: Database command inside a loop

Flags a DbCommand execution inside a loop body. Each iteration pays a database round trip. The rule does not require an await, because the round trip is paid either way.

The rule reads ExecuteNonQueryAsync, ExecuteScalarAsync, and ExecuteReaderAsync. The receiver must derive from DbCommand. E128093 owns the synchronous method shape, so this rule does not report it.

Exclusions:

  • A for loop with a compile-time constant bound.
  • A call in a loop header.
  • A loop body that calls Task.Delay or Thread.Sleep.

No code fix. The batch boundary depends on the transaction scope.

E128205: Collection filled in a loop with a known count

Flags a List<T>, Dictionary<K,V>, HashSet<T>, Queue<T>, or Stack<T> created with no capacity, when the next statement fills it in a loop with a known count.

List<int> result = new();
foreach (int item in source)
{
    result.Add(item);
}

The fix passes the count to the constructor:

List<int> result = new(source.Count);

The loop must be the next statement. The count comes from the foreach source or from a Count or Length bound in a for condition. The source expression must be a chain of names, not a call, so the fix never runs it twice. The resolved type must expose a public (int) constructor, so SortedSet<T> and SortedDictionary<K,V> stay silent.

Exclusions:

  • A loop with a break that exits this loop. A break inside a nested loop or a switch section does not count.
  • A collection that is not filled by the type’s own fill method, which is Add, Enqueue, or Push.
  • A capacity already set in an object initializer.

E128206: Empty loop body

Flags a while or do loop with an empty body. The loop spins a core until another thread changes the condition.

The rule stays silent when the condition calls a method. A while (reader.Read()) loop does its work in the condition, so it is not a spin.

No code fix. The signal type is a caller decision.

E128207: Reflection lookup inside a loop

Flags a System.Type member lookup inside a loop body. The lookup walks metadata and allocates on every iteration.

The rule reads GetProperty, GetMethod, GetField, GetMember, GetConstructor, GetEvent, GetNestedType, and GetInterface.

Exclusions:

  • A lookup that references a loop variable, as in item.GetType(). The receiver changes per iteration, so a hoist is wrong.
  • A for loop with a compile-time constant bound.
  • A lookup outside a loop. E128090 owns test methods.

The code fix hoists the lookup into a local declared before the loop and rewrites the call to read the local. The derived local name is unique in the member. It declines when the loop body assigns any local that the lookup reads. It offers no fix-all.

E128208: ContainsKey then indexer on a ConcurrentDictionary

Flags map.ContainsKey(key) as the condition of an if that then reads map[key]. The pair does two lookups and races with a concurrent writer that removes the key between them.

Use TryGetValue:

return map.TryGetValue(key, out int value) ? value : 0;

The rule reads ConcurrentDictionary<TKey,TValue> only. CA1854 covers Dictionary<K,V>.

The code fix rewrites the condition to TryGetValue and replaces each indexer read in the if body with the out local. The key must carry no call, so it is not evaluated twice with different behavior. The fix declines a body that writes the map, a read inside a lambda or local function, and a body that already declares the derived local name. It offers no fix-all.

E128209: GetBytes length inside a loop

Flags Encoding.GetBytes(value).Length inside a loop body. The call allocates a byte array only to read its length. GetByteCount returns the same number with no allocation.

The fix rewrites Encoding.UTF8.GetBytes(value).Length to Encoding.UTF8.GetByteCount(value). The receiver must derive from Encoding.

No exclusion beyond the loop and the .Length use.

E128210: new Regex inside a loop

Flags a Regex construction inside a loop body. Each iteration compiles the pattern.

The rule reads every Regex construction inside a loop body, including a constant pattern. The creation must not reference a value that changes per iteration, because a hoist is then wrong. A local declared in the loop body and a call inside the pattern both count as per-iteration values.

The code fix hoists the construction into a local declared before the loop and rewrites the creation to read the local. It declines when the loop body assigns any local that the creation reads. It offers no fix-all.

E128211: Task.Delay in a loop without a token

Flags Task.Delay inside a loop body when the resolved overload has no CancellationToken parameter. The wait does not observe cancellation.

A Task.Delay(delay, cancellationToken) call stays silent. So does a loop whose condition reads a CancellationToken, such as while (!token.IsCancellationRequested). Thread.Sleep is not this rule.

No code fix. The token source is a caller decision.

E128212: ToCharArray used only to index or iterate

Flags string.ToCharArray() when the result is the direct foreach source or the receiver of an element access. The copy serves no purpose because indexing and iteration work on the string directly.

foreach (char c in value.ToCharArray())

An array assigned to a local or passed to a method stays silent.

Code fix drops the call when it is a foreach source or an element access receiver.

E128213: Activator.CreateInstance inside a loop

Flags Activator.CreateInstance inside a loop body. Reflection runs on every iteration.

A for loop with a compile-time constant bound stays silent, because the total work is bounded.

No code fix. The cached factory shape is a caller decision.

E128214: HTTP handler without automatic decompression

Flags new HttpClientHandler() and new SocketsHttpHandler() when neither the object initializer nor a later assignment on the same local sets AutomaticDecompression. The default is DecompressionMethods.None, so a compressed response stays compressed.

new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All }

A derived handler type stays silent because its constructor may set the property. A field or property initializer stays silent, because a constructor can set the property later.

Automatic decompression decodes any response the handler reads. Enable it for trusted origins, and cap the response size or stream with a byte limit when the origin is untrusted.

No code fix. The decompression method set is a caller decision.

E128215: StringBuilder without capacity for a known append count

Flags new StringBuilder() with no arguments when the next statement is a loop that calls Append or AppendLine on the builder and the loop count is known. The builder grows and copies its buffer as it fills.

The count comes from the foreach source or a Count or Length bound in a for condition. The source expression must be a chain of names, not a call.

A loop with a break that exits this loop stays silent, because it can stop early. A break inside a nested loop or a switch section does not count. An append inside a lambda or local function does not run during the loop, so it does not count. A constructor with a capacity or an initial string stays silent, and so does a capacity set in an object initializer.

The code fix inserts the known count as the capacity argument. The count expression is the pure member chain the rule already computed. The estimate stays a lower bound, and an underestimate only costs a later growth.

E128216: Unbounded channel

Flags Channel.CreateUnbounded<T>() and Channel.CreateUnboundedPrioritized<T>(). An unbounded channel grows without limit when producers outrun consumers.

Use Channel.CreateBounded<T>(capacity) when the producer rate is not bounded.

No code fix. The capacity and full-mode policy are caller decisions.

E128217: Large struct passed by value

Flags a parameter of a source-declared struct larger than 24 bytes, passed by value. Each call copies the whole struct.

The size sums instance fields. A reference or pointer field counts as 8 bytes. The rule handles fixed buffers, inline arrays, nullable structs, and enums. SIMD and System.Numerics types stay silent.

The message reports a lower bound, because the estimate ignores padding. A self-referential or deeply nested struct stops at a fixed depth instead of recursing without end.

Exclusions:

  • An in, ref, out, params, or this parameter.
  • An override, an interface declaration, or an interface implementation, where the signature is fixed.
  • A struct declared outside the current compilation, such as a framework type.
  • An explicit-layout struct, whose fields overlap.

No code fix. The in modifier or a class change is a caller decision.

E128223: Hand-rolled child-process capture

Flags a process launch that redirects a standard stream, reads the stream with ReadToEnd or ReadToEndAsync, and then waits for exit. Process.RunAndCaptureText and Process.RunAndCaptureTextAsync return the standard output, the standard error, and the exit status in one call.

The rule binds the redirect flag to the process through the start info member, a start info local passed to Process.Start, a start info assigned to the process, or a process object initializer. A redirect on another process, a read on another process, or a read after the wait stays silent.

A launch that redirects standard input stays silent, because the caller interacts with the child. A line read stays silent, because the caller stops early. The rule carries no code fix, because the replacement changes the error handling around the launch.

// Before (warns)
using var process = Process.Start(new ProcessStartInfo(file)
{
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false
});
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();

// After
var result = Process.RunAndCaptureText(new ProcessStartInfo(file)
{
    RedirectStandardOutput = true,
    RedirectStandardError = true,
    UseShellExecute = false
});
string output = result.StandardOutput;
string error = result.StandardError;
int exitCode = result.ExitStatus.ExitCode;

E128224: MemoryStream wraps a read-only source

Flags a MemoryStream that wraps a string or a byte array and is read only. StringStream wraps the string without a copy, and ReadOnlyMemoryStream wraps the bytes without a copy.

The rule reads one method body. A write call, an assignment or increment to a settable member such as Position, a buffer read through ToArray, an unknown consumer, a return, or a store into another member keeps the report silent, because the target types reject a write. A compression wrapper (GZipStream, DeflateStream, or BrotliStream) counts as a consumer only when it is constructed with CompressionMode.Decompress, because a compress mode or a missing mode writes to the inner stream. The rule carries no code fix for the same reason.

// Before (warns)
using var stream = new MemoryStream(Encoding.UTF8.GetBytes(text));
using var reader = new StreamReader(stream);

// After
using var stream = new StringStream(text, Encoding.UTF8);
using var reader = new StreamReader(stream);

E128226: Comparer set built by a loop

Flags a HashSet<T> that a comparer constructor creates and a later loop fills. The collection expression [with(StringComparer.X), .. items] passes the comparer as an argument and fills the set in one statement.

A collection initializer, a field declaration, a set that escapes to another method, and an Add call outside the loop keep the report silent.

The code fix rewrites the declaration and the fill loop into the collection expression. It applies when the loop body is exactly the Add call with the iteration variable. It declines an Add inside a lambda, a while or for fill, and a compiler below C# 12.

// Before (warns)
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var item in items)
{
    set.Add(item);
}

// After
HashSet<string> set = [with(StringComparer.OrdinalIgnoreCase), .. items];

E128271: MemoryStream round trip copies a byte array

Flags new MemoryStream(bytes).ToArray() when bytes is a byte[] and the creation carries one argument. MemoryStream wraps the array without a copy, and ToArray allocates a second array with the same bytes. Use the original array for a read-only view, or Clone it when the caller needs an independent copy. A stream held in a local, a creation with more than one argument, and any other ToArray source stay silent. The rule reports at info and carries no code fix, because the copy is sometimes the ownership boundary.

// Warns: the copy repeats the array
byte[] copy = new MemoryStream(bytes).ToArray();

// Correct for a read-only view
ReadOnlyMemory<byte> view = bytes;

E128229: Middleware binds the Func<Task> next delegate

Flags an inline Use middleware whose second parameter is a Func<Task>. The app.Use((context, next) => ...) overload allocates a Func<Task> closure on every request. The RequestDelegate overload passes the same delegate with no allocation.

The rule reports only when every use of next is a call with no argument, at least one such call exists, and the lambda never reassigns the context parameter. The fix changes the parameter type to RequestDelegate and passes the context to every call. The rule also accepts the manual IApplicationBuilder.Use overload, not only the extension method.

// Before (warns)
app.Use(async (HttpContext context, Func<Task> next) =>
{
    await next();
});

// After
app.Use(async (HttpContext context, RequestDelegate next) =>
{
    await next(context);
});

E128230: Static files served through the runtime pipeline

Flags app.UseStaticFiles() with no argument. The call runs a request-time middleware. MapStaticAssets serves a build-time manifest with precompressed variants and ETags.

The rule registers only when the compilation declares MapStaticAssets, so a target framework without the endpoint mapping API gets no report. A call that passes StaticFileOptions stays silent, because the rewrite moves the call into the endpoint mapping section. The rule carries no code fix, because a Razor app also changes how it references the assets.

// Before (warns)
app.UseStaticFiles();

// After
app.MapStaticAssets();

E128231: Split result enumerated without a stored array

Flags a foreach that enumerates a string.Split result with a char or constant-string separator. The call allocates one array and one string per part. MemoryExtensions.Split yields Range values over the same string with no allocation.

The rule reports the loop. The fix changes the source to source.AsSpan().Split(separator) and reads each part as a slice of the span. The fix applies only when every read of the part is a length, an element access, or a constant-string comparison, and the receiver is a name chain. A loop that passes the part to a method or parses it stays reported with no fix, because Parse takes a ReadOnlySpan<char> only with an explicit format provider.

// Before (warns)
foreach (string part in line.Split(','))
{
    total += part.Length;
}

// After
foreach (var part in line.AsSpan().Split(','))
{
    total += line.AsSpan()[part].Length;
}

E128233: Parallel.For runs one delegate per item

Flags a three-argument Parallel.For(from, to, body) over an int or long range whose synchronous body holds no loop and no await. The runtime invokes one delegate per index. A range partition invokes one delegate per chunk. The body may take the item alone or the item and a ParallelLoopState.

The fix rewrites the call to Parallel.ForEach(Partitioner.Create(from, to), range => ...) with the original body inside a for loop over the range, and adds using System.Collections.Concurrent; when absent. It handles positional and named arguments, a lambda body, and a method group. An async body binds as async void, so the rule reports it with the Parallel.ForEachAsync remedy and offers no fix. The rule stays silent on a body that mutates its item parameter, a body that already loops or uses the name range, the For<TLocal> overload, and a user-defined For.

// Before (warns)
Parallel.For(0, items.Count, i => Work(items[i]));

// After
Parallel.ForEach(Partitioner.Create(0, items.Count), range =>
{
    for (int i = range.Item1; i < range.Item2; i++)
    {
        Work(items[i]);
    }
});

E128235: Readonly field re-read inside a loop

Flags a loop that reads a readonly array field of the enclosing type once per iteration. A local copy declared before the loop lets the JIT drop the repeated field load and the bounds check.

The fix inserts one local before the loop and rewrites the field references inside that loop only. The local name derives from the field name and falls back to a suffix on a collision. The rule stays silent on a mutable field, because a concurrent writer could change it and the copy would hide the change. A nested loop stays silent, because the outermost fix rewrites the whole cluster.

// Before (warns)
for (int i = 0; i < _items.Length; i++)
{
    total += _items[i];
}

// After
int[] items = _items;
for (int i = 0; i < items.Length; i++)
{
    total += items[i];
}

E128247: Readonly field of a mutable struct

Flags a readonly field whose type is a mutable struct. The compiler copies the whole struct out of the field before every member call.

A readonly struct type, a primitive, an enum, a tuple, a ref struct, and a struct with no mutable instance member stay silent. The rule carries no code fix, because the answer is to make the struct readonly or to change where the value lives.

struct Counter { public int Value; public void Increment() => Value++; }

// Before (warns)
private readonly Counter _counter = default;

// After
private Counter _counter = default;

E128249: Array regrown inside a loop

Flags Array.Resize in a loop body and Enumerable.Concat whose sequence is assigned back to the same variable. Every iteration reallocates and copies, so the loop costs quadratic time.

A call outside a loop, a lambda body, and a Concat assigned to a different variable stay silent. The rule carries no code fix, because a presized array or a builder depends on the loop.

// Before (warns)
for (var i = 0; i < items.Length; i++)
{
    Array.Resize(ref buffer, buffer.Length + 1);
}

// After
var buffer = new List<byte>(items.Length);
for (var i = 0; i < items.Length; i++)
{
    buffer.Add(items[i]);
}

E128253: Struct dictionary or set key without IEquatable<T>

Flags a Dictionary<TKey, TValue>, HashSet<T>, or ConcurrentDictionary<TKey, TValue> created with the default equality comparer where the key is a source struct that does not implement IEquatable<T>.

EqualityComparer<T>.Default falls back to an object comparer for such a key. Each hash and equality test then boxes the key. Add IEquatable<T> to the struct, or pass a comparer that avoids boxing.

The report stays silent when the key comes from metadata, implements IEquatable<T>, or the creation passes an IEqualityComparer<T> argument. It also stays silent for an enum key, because the runtime compares an enum through its underlying value without boxing. A value tuple key also stays silent, because a tuple type implements IEquatable of its underlying tuple type. A collection expression that fills a set reaches no object creation, so that form is outside the rule. The rule carries no code fix, because the remedy adds a member to the key type.

struct Point
{
    public int X;
    public int Y;
}

// Before (warns)
var points = new Dictionary<Point, string>();

// After
readonly record struct Point(int X, int Y);
var points = new Dictionary<Point, string>();

E128255: Use TensorPrimitives.Add/Multiply instead of an element-wise loop

Flags an indexed for loop whose body writes destination[i] = a[i] + b[i] or destination[i] = a[i] * b[i], where all three values are a float or double array, Span<T>, or ReadOnlySpan<T>.

The loop bound must be the length of one of the two sources. TensorPrimitives requires the two sources to have equal length and reads the first source for its length, so the fix passes the bound owner first and assumes equal-length sources. The destination must be at least as long as the first source. A bound on the destination stays silent, because the rule cannot prove that the destination is at least as long as both sources.

The rule stays silent when the body holds a second statement, when an index carries an offset, when an operand is not an element access, and when the element type is not float or double. It also stays silent when the compilation has no System.Numerics.Tensors assembly that declares the matching three-parameter member.

The double element type matches the generic Add<T> and Multiply<T> overloads, because the package declares non-generic members for float only.

The fix replaces the loop with TensorPrimitives.Add(a, b.AsSpan(0, a.Length), destination); and adds the System and System.Numerics.Tensors using directives. It slices the second source to the length of the first source, so a longer second source does not throw. The fix applies only when all three operands are arrays, because two arrays cannot overlap partially. A span operand keeps the diagnostic and offers no fix.