Replace the concurrent collections of MA0234 with locked collections

Merged
ME
2mo ago
+12-5

What changed

DoNotUseNotYetInitializedStaticFieldAnalyzer (MA0234) kept its per-type state in a ConcurrentBag<FieldReferenceInfo> and a ConcurrentDictionary<IFieldSymbol, bool> used as a set. Both are now a List<T> and a HashSet<T> guarded by a lock.

Why

The analyzer allocates one AnalyzerContext per named type that declares a static field, so these two collections are allocated thousands of times in a large compilation. Both are write-only during the operation actions and enumerated once in the symbol end action — the workload these concurrent collections are the worst at:

  • ConcurrentBag<T> is built for same-thread add/take via work-stealing thread-local queues. Nothing is ever taken here, so that machinery buys nothing. Each instance allocates a ThreadLocal<T> plus per-thread queue infrastructure (and ThreadLocal ids are a globally managed resource that widens every participating thread's slot table). Enumerating it freezes the bag by taking every per-thread lock and copies the whole content into a List<T> snapshot.
  • ConcurrentDictionary<T, bool> allocates a bucket table plus a lock array sized to Environment.ProcessorCount on construction.

A List<T> and a HashSet<T> allocate nothing but the object until the first add, and the adds are rare — they only happen for field references inside static field initializers or assignments in a static constructor — so lock contention is negligible.

Notes for reviewers

  • lock (_collection) around a plain collection is the pattern already used by ClassMustBeSealedAnalyzer, MakeClassStaticAnalyzer and AvoidUnusedInternalTypesAnalyzer in this repository.
  • Enumeration in ReportDiagnostics needs no lock: Roslyn guarantees the symbol end action runs after all the operation actions registered in the symbol start action. A comment records this.
  • SymbolEqualityComparer.Default still works as the HashSet<IFieldSymbol> comparer through IEqualityComparer<T> contravariance.
  • The fieldDeclarationInfos cache stays a ConcurrentDictionary: it is a single, read-heavy instance shared by every context of the compilation, which is what that type is good at.
  • No behavior change, so no documentation change. dotnet run --project src/DocumentationGenerator exits 0 with no markdown changes.

Validation

  • Build clean, 0 warnings.
  • The 16 MA0234 tests pass on both roslyn5.9 and roslyn4.8.