Skip to content

Share Roslyn metadata references across AssemblyGenerator compilations (#1086) - #1089

Merged
jeremydmiller merged 1 commit into
mainfrom
fix/1086-cache-metadata-references
Oct 28, 2026
Merged

jeremydmiller merged 1 commit into
mainfrom
fix/1086-cache-metadata-references

Conversation

@jeremydmiller

Copy link
Copy Markdown
Member

Fixes #1086

Problem

AssemblyGenerator.Compile() builds a new generator per call and calls MetadataReference.CreateFromFile() for every reachable assembly (~200 in a typical ASP.NET Core app). Roslyn prefetches the entire image into native memory that is only released on finalization. The managed heap barely moves, so the GC rarely runs and native memory grows by ~60-100 MB per compilation — e.g. many in-process hosts in a test run, each compiling in TypeLoadMode.Dynamic.

Fix

  • A process-wide ConcurrentDictionary<string, MetadataReference> keyed by assembly path; every generator reuses the same (immutable, thread-safe) PortableExecutableReference.
  • Per-generator de-duplication uses a HashSet<string> of paths instead of a linear _references.Any(x => x.Display == path) scan (same ordinal semantics).
  • No public API change (an internal References accessor for tests).

Measurements

The issue's compiler repro, 15 × AssemblyGenerator.Compile, no forced GC, working set on macOS:

compile 1 compile 6 compile 15 per compile after first
before 208 MB 494 MB 600 MB (climbing) 14–21 ms
after 189 MB 194 MB 198 MB (flat) 1–3 ms

Tests

Bug_1086_metadata_references_are_shared: separate generators share the same reference instances, each path is referenced once, repeated compiles still work. All 495 CodegenTests pass on net10.0.

🤖 Generated with Claude Code

#1086)

MetadataReference.CreateFromFile() copies the whole PE image into native
memory that is only released on finalization. AssemblyGenerator.Compile()
created a fresh reference for every reachable assembly on every call, so
processes that compile repeatedly grew native memory by ~60-100 MB per
compilation while the managed heap stayed too small to trigger a GC.

Cache one MetadataReference per assembly path for the whole process and
reuse it in every generator. Per-generator de-duplication now uses a
HashSet of paths instead of a linear scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant