Reduce the CPU and the memory used by the rules

Merged
ME
2mo ago
+505-346

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 GetEnclosingSymbol on 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 calls EnableConcurrentExecution, 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: IsImmutableCreateMethod ran for nearly every invocation and allocated two arrays and a LINQ closure before the cheap Arity/Name test. Reordered, allocation-free.
  • MA0020 and the other LINQ rules: ExtensionMethodOwnerTypes.Contains(type, SymbolEqualityComparer.Default) is Enumerable.Contains over a List<>, 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 used List<T>.Contains without the symbol comparer.
  • MA0131: a name comparison before the symbol hash lookup.
  • MA0035: GetTypesByMetadataName moved into RegisterCompilationStartAction.
  • MA0023: HasUnnamedGroups built two Regex per call site, parsing the pattern twice. The result is a pure function of (pattern, options), so it is memoized in a BoundedCache, like the configuration patterns already are.
  • Configuration options: ChangeType<T> converted through (T)(object), boxing on every read of a bool or int option. It now uses Unsafe.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 ReferenceLocation struct is passed by ref on purpose: Resolve() caches into the struct, so a defensive copy would lose the caching. It is deliberately not marked readonly.
  • The Unsafe.As change also removed two throw new InvalidOperationException branches in ChangeType<T>. They were unreachable: inside if (typeof(T) == typeof(bool)), the defaultValue is bool pattern always succeeds.
  • These are static-reasoning improvements; they have not been benchmarked.

Verification

  • dotnet build on the solution: 0 warnings, 0 errors, for both net10.0 and netstandard2.0.
  • dotnet run --project src/DocumentationGenerator exits 0 with no change to docs/.
  • 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.