Reduce the CPU and the memory used by the rules
Several rules did expensive work on every operation of the compilation before checking the cheap conditions that would discard the result. This reduces that work. No rule changes its behavior: all the reorderings are guarded by conditions that are provably equivalent to the ones they replace.
What changed
MA0182 (AvoidUnusedInternalTypes) is the largest one. It registers on 11 operation kinds (Invocation, PropertyReference, FieldReference, Conversion, VariableDeclarator, …) and analyzes generated code, so it runs on nearly every operation of the compilation. Each call:
- queried
GetEnclosingSymbolon the semantic model, although the enclosing type is only used to ignore the references a type makes to itself; - took
lock (_usedTypes), although the analyzer callsEnableConcurrentExecution, so every analysis thread ended up on the same monitor.
The enclosing type is now resolved through a ReferenceLocation struct threaded by ref through the recursion: it is resolved at most once, and only when a type of the analyzed assembly is reached. That is safe because the reference location is always a source type, so it can never be equal to a type coming from a reference — which is exactly the condition ShouldConsiderType already tested. The lock is replaced by the existing ConcurrentHashSet.
MA0036 (MakeClassStatic) had the same global lock, and stored every type it saw, including all the BCL types, although the set is only used to exclude the candidates, which are all declared in the analyzed assembly. The referenced types are still walked, as they can carry a type of the assembly as a type argument (List<MyClass>), they are just not kept.
MA0042/MA0045 (DoNotUseBlockingCallInAsyncContext) ran the full FindAsyncEquivalent overload search on every call, and only then checked CanBeAsync / IsAsyncContext / CanChangeParentMethodSignature before discarding the result. In a synchronous codebase, that search was pure waste. The check now runs first. The three checks are merged into a single GetAsyncContextKind returning a three-state enum, so GetEnclosingSymbol runs once instead of twice, and the Ancestors().Any(…) walk became an allocation-free parent loop.
MA0003 (UseNamedParameter) called SemanticModel.GetOperation before MustCheckExpressionKind. With the default configuration (Null | Boolean), every numeric and string literal argument of the compilation was bound and then dropped. The configuration is now read before binding. The declaration id of the called method is also built once for the two exclusion options instead of twice.
Smaller hot paths:
- MA0065:
IsImmutableCreateMethodran for nearly every invocation and allocated two arrays and a LINQ closure before the cheapArity/Nametest. Reordered, allocation-free. - MA0020 and the other LINQ rules:
ExtensionMethodOwnerTypes.Contains(type, SymbolEqualityComparer.Default)isEnumerable.Containsover aList<>, which boxes an enumerator per invocation, for a list of at most two entries. Replaced by a direct comparison against the two cached symbols (6 call sites). This also fixes an inconsistency, as one of the call sites usedList<T>.Containswithout the symbol comparer. - MA0131: a name comparison before the symbol hash lookup.
- MA0035:
GetTypesByMetadataNamemoved intoRegisterCompilationStartAction. - MA0023:
HasUnnamedGroupsbuilt twoRegexper call site, parsing the pattern twice. The result is a pure function of(pattern, options), so it is memoized in aBoundedCache, like the configuration patterns already are. - Configuration options:
ChangeType<T>converted through(T)(object), boxing on every read of aboolorintoption. It now usesUnsafe.As.
Separate commit: supported diagnostics
SupportedDiagnostics was an expression-bodied property calling ImmutableArray.Create, allocating a new backing array on every access. It is now an auto-property initialized once. Roslyn's AnalyzerManager caches the descriptors, so the win is small — this is mostly hygiene. It is a one-line change in each of the 165 analyzers, isolated in its own commit (c304d99) to keep the diff of the actual work reviewable.
Notes for the reviewer
- The
ReferenceLocationstruct is passed byrefon purpose:Resolve()caches into the struct, so a defensive copy would lose the caching. It is deliberately not markedreadonly. - The
Unsafe.Aschange also removed twothrow new InvalidOperationExceptionbranches inChangeType<T>. They were unreachable: insideif (typeof(T) == typeof(bool)), thedefaultValue is boolpattern always succeeds. - These are static-reasoning improvements; they have not been benchmarked.
Verification
dotnet buildon the solution: 0 warnings, 0 errors, for bothnet10.0andnetstandard2.0.dotnet run --project src/DocumentationGeneratorexits 0 with no change todocs/.- Tests pass on every supported Roslyn version: roslyn4.8 4811, roslyn4.14 4843, roslyn5.0 4875, roslyn5.6 4899, roslyn5.9 4932. 0 failed, 0 skipped.