Skip to content

[TrimmableTypeMap] Optimize build times #10958

Closed as not planned
1 of 9 issues completed
Closed as not planned

Description

@simonrozsival

Part of #10788

Track build-time optimization opportunities for the trimmable type map generation pipeline (GenerateTrimmableTypeMap task).

Current performance (PR #10924 benchmarks, MacBook M1)

Phase Avg P50 P95
Scan (8870 types) 235ms 224ms 319ms
Emit (typemap assemblies) 86ms 75ms 181ms
JCW (315 Java files) 766ms 409ms 3167ms
Total cold 1088ms 702ms
Total incremental (scan only) 221ms 215ms

Optimization opportunities

Sub-issues

Sub-issues

1 of 9 Issues completed
Loading 9 sub-issues

Activity

  1. added this to the .NET 11 milestone on Mar 17, 2026
  2. added
    needs-triage
    on Mar 17, 2026
  3. removed
    needs-triage
    on Mar 17, 2026
  4. simonrozsival commented on Mar 17, 2026

    @simonrozsival
    MemberAuthor

    PR #10959 adds per-assembly acw-map.{AssemblyName}.txt files as a side-output of GenerateTrimmableTypeMap. When optimizing incremental builds (e.g., per-assembly Inputs/Outputs or the two-list Scan overload), the acw-map files should be included in the incrementality story:

    • If an assembly is unchanged and its scan is skipped, the per-assembly acw-map file should also be preserved (not regenerated)
    • AcwMapWriter.WriteToFile already does content comparison to avoid unnecessary timestamp updates, but skipping the write entirely (when the scan is skipped) would be even better
    • The _MergeAcwMaps target uses Inputs/Outputs on the per-assembly files, so it will automatically skip if no acw-map file was touched

    Adding this as a consideration item for the incremental build optimization work.

  5. simonrozsival commented on Mar 31, 2026

    @simonrozsival
    MemberAuthor

    Additional optimization: XDocument → XmlReader/XmlWriter for manifest generation

    The manifest generator currently uses System.Xml.Linq (XDocument/XElement) which builds a full DOM tree in memory. For forward-only XML operations (e.g., reading the template manifest, writing the final output), XmlReader/XmlWriter would be more efficient — streaming and allocation-free.

    Challenge: The current manifest generation requires read-modify-write semantics (load template → query existing elements for dedup → add new elements → save). This inherently needs a DOM. A pure XmlReader/XmlWriter approach would require building a custom in-memory model or restructuring the merge logic into a single streaming pass.

    Potential approach:

    • Read template with XmlReader, build a lightweight custom model (just element names + attributes for dedup)
    • Generate new elements directly
    • Write everything with XmlWriter in a single pass

    Raised by @jonathanpeppers in #11035 (review)

  6. simonrozsival commented on Apr 7, 2026

    @simonrozsival
    MemberAuthor

    Follow-up from PR #11037: we prototyped broader incremental invalidation for _GenerateTrimmableTypeMap by hashing manifest-affecting MSBuild properties into an inputs cache file, but we are deferring that change to this issue to keep the manifest-rooting PR focused. If we pick this up here later, commit e9d0850 has a starting point for the approach.

  7. simonrozsival commented on Apr 23, 2026

    @simonrozsival
    MemberAuthor

    Split trimmable typemap generation into per-assembly MSBuild tasks for incremental builds

    Problem

    The trimmable typemap generator runs as a single monolithic MSBuild task (GenerateTrimmableTypeMap) that takes all assemblies, scans them sequentially, and produces all typemap DLLs in one invocation. This means any assembly change triggers a full regeneration of every typemap DLL — even if only one app assembly was modified. For Debug inner-loop builds, this is unnecessarily slow.

    Proposed design

    Core idea

    Split the monolithic task into per-assembly invocations. Each invocation scans one input assembly (with reference assemblies available for type hierarchy resolution) and produces one typemap DLL. A downstream task generates the entry-point assembly.

    The granularity depends on configuration:

    • Debug: one assembly per task invocation → maximum incremental build granularity
    • Release: all assemblies in one invocation → shared typemap universe with cross-assembly alias merging

    Task 1: GenerateTypeMapUnit

    Invoked once per "unit" of assemblies.

    • Input assemblies: the assemblies to scan for Java peer types (one in Debug, all in Release)
    • Reference assemblies: other assemblies needed only for resolving base type hierarchies, interface implementations, and activation constructors — loaded lazily, only when TryResolveType encounters a cache miss
    • Output: one typemap DLL + JCW Java sources
    • Cross-assembly alias merging happens within the unit (irrelevant for single-assembly Debug units; handles shared universe in Release)

    Task 2: GenerateEntryPointTypeMap

    Invoked once after all unit tasks complete.

    • Input: list of per-unit typemap DLL names
    • Output: _Microsoft.Android.TypeMaps.dll (entry-point assembly with TypeMapLoader.Initialize())
    • For Debug: aggregates all per-assembly typemap references
    • For Release: minimal — the single unit already produced the complete typemap

    Debug vs Release flow

    Debug (per-assembly units):
    
    [Assembly A] ──Task 1──→ _A.TypeMap.dll
    [Assembly B] ──Task 1──→ _B.TypeMap.dll  ──Task 2──→ _Microsoft.Android.TypeMaps.dll
    [Assembly C] ──Task 1──→ _C.TypeMap.dll     (aggregates references)
    
    Release (single unit):
    
    [All assemblies] ──Task 1──→ typemap DLLs  ──Task 2──→ _Microsoft.Android.TypeMaps.dll
                       (alias merging here)        (just entry point)
    

    Incremental builds via assembly dependency graph

    For MSBuild Inputs/Outputs to give precise incrementality, each unit task needs to know exactly which assemblies could affect its output — not just the input assembly, but every transitive dependency that could contribute Java peer types.

    Pre-task: ComputeTypeMapDependencies

    A lightweight pre-task reads each assembly's AssemblyRef metadata table (System.Reflection.Metadata, microseconds per assembly) and builds the transitive dependency graph.

    Assembly A:
      AssemblyRef: A → Mono.Android, A → MyLibrary, A → System.Runtime
      Mono.Android → Java.Interop, Mono.Android → System.Runtime
      MyLibrary → Mono.Android
    
      Full transitive closure: {Mono.Android, Java.Interop, MyLibrary, System.Runtime}
    

    Pruning: only Java-peer-bearing assemblies matter

    An assembly can only contain Java peer types ([Register], [JniTypeSignature]) if it references Mono.Android or Java.Interop (directly or transitively). Assemblies like System.Runtime, System.Text.Json, etc. can never affect the typemap. The pre-task prunes the dependency graph by checking AssemblyRef entries — if an assembly's transitive closure doesn't include Mono.Android or Java.Interop, it's excluded from the dependency set.

    Pruned dependency set for A: {Mono.Android, Java.Interop, MyLibrary}
    (System.Runtime excluded — no path to Mono.Android or Java.Interop)
    

    MSBuild integration

    <!-- Fast pre-task: read AssemblyRef tables, build dependency graph -->
    <ComputeTypeMapDependencies
        Assemblies="@(ResolvedAssemblies)">
      <Output TaskParameter="PerAssemblyDependencies" ItemName="_TypeMapInput" />
    </ComputeTypeMapDependencies>
    
    <!-- Per-unit typemap generation with precise Inputs -->
    <GenerateTypeMapUnit
        InputAssembly="%(_TypeMapInput.Identity)"
        ReferenceAssemblies="%(_TypeMapInput.Dependencies)"
        Inputs="%(_TypeMapInput.Identity);%(_TypeMapInput.Dependencies)"
        Outputs="$(IntermediateOutputPath)typemaps\_%(_TypeMapInput.Filename).TypeMap.dll" />
    
    <!-- Entry-point assembly -->
    <GenerateEntryPointTypeMap
        PerUnitTypeMapDlls="@(_GeneratedTypeMapDlls)"
        OutputPath="$(IntermediateOutputPath)typemaps\_Microsoft.Android.TypeMaps.dll" />

    Incrementality in practice

    During typical inner-loop development:

    • Developer changes MyApp.dll → only _MyApp.TypeMap.dll is rebuilt
    • Mono.Android.dll, Java.Interop.dll, library DLLs are all stable → their typemap DLLs are untouched
    • Entry-point assembly regeneration is cheap (just emits references to per-assembly DLLs)

    On SDK/NuGet update:

    • Mono.Android.dll changes → all typemaps that transitively depend on it are rebuilt
    • This is correct and expected — base type hierarchies may have changed

    Lazy reference assembly loading

    The scanner (JavaPeerScanner) currently calls AssemblyIndex.Create for every assembly upfront, eagerly building full metadata indices. When scanning a single input assembly, most reference assemblies are never touched — the scanner only reads them when walking inheritance chains or resolving interfaces.

    Reference assemblies should be indexed on demand — only when TryResolveType encounters a cache miss for an assembly name in the reference set. This reduces per-task memory and startup time, especially for app assemblies with shallow inheritance hierarchies.

    Considerations

    • JCW generation is already per-peer and moves naturally into Task 1
    • Manifest generation needs the full peer list — should be a separate task or part of Task 2
    • Global passes (manifest rooting, deferred registration propagation) need the full peer list in Release; in Debug, they're scoped to the unit's peers + resolved references
    • ComputeTypeMapDependencies output can itself be cached — only recompute when the set of input assemblies changes

    Scope

    Optimization and refactoring. No behavioral changes to the generated typemaps or runtime behavior.

  8. simonrozsival commented on May 25, 2026

    @simonrozsival
    MemberAuthor

    Update after looking at main (ec8c61e1b):

    The current implementation is partially aligned with this issue. It has moved in the right structural direction, but the bigger build-time optimization design is still mostly open.

    What is implemented well:

    • The generator now emits per-assembly typemap DLLs plus _Microsoft.Android.TypeMaps, with Debug using per-assembly universes and Release using a shared typemap universe (useSharedTypemapUniverse: !Debug). This matches the proposed end shape better than the original single-output model.
    • _GenerateTrimmableTypeMap has target-level MSBuild incrementality via Inputs/Outputs, including references, the app assembly, manifest, and $(_AndroidBuildPropertiesCache), so no-op builds can skip the task entirely.
    • Outputs are mostly timestamp-preserving: typemap list, manifest, acw-map.txt, ApplicationRegistration.java, and JCW files use CopyIf*Changed-style writes. JCW files are no longer blindly rewritten.
    • Manifest handling has become more complete: manifest-referenced types are rooted, compat names are rewritten, and deferred registration is handled across Application/Instrumentation-related types.

    What still needs revisiting:

    • The task is still monolithic. GenerateTrimmableTypeMap receives all assemblies, opens all PEReaders, eagerly builds AssemblyIndex for every assembly, and scans everything sequentially. There is no GenerateTypeMapUnit, GenerateEntryPointTypeMap, ComputeTypeMapDependencies, per-assembly MSBuild Inputs/Outputs, or lazy reference assembly loading yet.
    • The in-task typemap DLL skip logic looks too coarse: WriteAssembliesToDisk() skips per-assembly typemap writes based only on the source assembly timestamp. If the target reruns because non-assembly inputs changed — manifest rooting inputs, package naming policy, max array rank, Debug/Release shared-universe mode, build properties, etc. — a typemap DLL could be considered “up to date” even though regenerated content would differ. This should be tightened before building more incrementality on top.
    • JCW generation is still sequential and still generates all source content before comparing/writing. CopyIfStreamChanged preserves timestamps, but it does not avoid generation or comparison cost. Parallel generation and/or cheaper content hashing remains worth revisiting.
    • Assembly scanning is still sequential/eager; scan-result caching across incremental builds is not implemented.
    • Manifest generation still uses XDocument/XElement. Given the current read-modify-write and dedup semantics, streaming is still non-trivial, but the earlier lightweight-model/single-pass-writer idea remains the likely path if this becomes a measurable cost.
    • I do not see per-assembly acw-map.{AssemblyName}.txt files or _MergeAcwMaps on current main; it currently writes one merged acw-map.txt. The earlier ACW-map incrementality note should be re-synced with the current implementation.

    Suggested status: mark target-level no-op incrementality and content-preserving writes as partial/done, but keep this issue open for the real per-assembly partial build split, dependency graph computation, scan/JCW parallelism, scan caching, and manifest streaming. Before the larger split, I’d prioritize revisiting the timestamp-only per-assembly typemap skip because it may create stale outputs when non-assembly inputs change.

  9. simonrozsival commented on May 25, 2026

    @simonrozsival
    MemberAuthor

    Baselines as of 2026-05-25

    I ran local baseline measurements for the Debug/Release × MonoVM/CoreCLR × llvm-ir/trimmable matrix.

    Startup clean/no-op/incremental use virtually identical APKs, so I combined those 30 launches into one startup average per config. APK size is the median of the preserved representative clean/no-op/incremental APKs for that config. For the CoreCLR+trimmable cases where Android did not emit TotalTime, I reran the missing measurements under caffeinate; Android still emitted only WaitTime, so the * startup values include WaitTime fallback samples.

    Environment: .NET SDK 11.0.100-preview.5.26258.110, MSBuild 18.8.0-preview-26258-110, macOS arm64 host, Samsung arm64-v8a device (R58Y30HZ65V). The test project used <TrimMode>full</TrimMode>.

    Configuration Runtime Typemap APK size Clean build median No-op build median Incremental build median Startup avg Startup median Startup samples
    Debug MonoVM llvm-ir 38.50 MiB 55,244 ms 8,706 ms 41,633 ms 582 ms 566 ms 30
    Debug CoreCLR llvm-ir 57.37 MiB 31,730 ms 5,587 ms 26,100 ms 742 ms 718 ms 30
    Debug CoreCLR trimmable 57.83 MiB 39,332 ms 24,167 ms 33,784 ms 803 ms* 792 ms* 30 (10 WaitTime fallback)
    Release MonoVM llvm-ir 3.64 MiB 22,941 ms 4,477 ms 16,483 ms 330 ms 328 ms 30
    Release CoreCLR llvm-ir 7.32 MiB 23,161 ms 5,728 ms 17,956 ms 373 ms 371 ms 30
    Release CoreCLR trimmable 8.19 MiB 29,576 ms 11,312 ms 29,003 ms 574 ms* 574 ms* 30 (30 WaitTime fallback)

    A few takeaways:

    • Debug build times are high across the board, especially MonoVM+llvm-ir clean/incremental and CoreCLR+trimmable no-op/incremental.
    • CoreCLR startup is slower than MonoVM in both Debug and Release for llvm-ir.
    • Release CoreCLR+trimmable startup is notably slower than Release CoreCLR+llvm-ir, even with the WaitTime caveat.

    These numbers give us a baseline to improve against: we need to drive down both build times and startup performance. 🚀

  10. jonathanpeppers commented on Aug 12, 2026

    @jonathanpeppers
    Member

    Closing this umbrella issue as superseded by the focused follow-up issues created from its remaining work:

    No-op target incrementality and timestamp-preserving output writes have already landed. The focused issues provide clearer ownership and completion criteria for the remaining optimization work, so this umbrella no longer needs to remain open.

  11. locked and limited conversation to collaborators on Sep 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions