Repository navigation
Closed as not planned
Task
1 / 91 of 9 issues completed
Copy link
Labels
Milestone
Description
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
- Parallelize JCW source generation — each Java file generation is independent; running them in parallel could significantly reduce the JCW phase which dominates cold build time (suggested by @elinor-fung in [TrimmableTypeMap] Add GenerateTrimmableTypeMap MSBuild task and targets #10924 (comment))
- Parallelize assembly scanning — scanning assemblies for Java peers could be parallelized across assemblies (suggested by @elinor-fung in [TrimmableTypeMap] Add GenerateTrimmableTypeMap MSBuild task and targets #10924 (comment))
- Use MSBuild partial builds — replace the in-task timestamp checking with MSBuild native
Inputs/Outputs1-1 mapping so MSBuild only passes changed assemblies to the task, eliminating the stamp file (suggested by @jonathanpeppers in [TrimmableTypeMap] Add GenerateTrimmableTypeMap MSBuild task and targets #10924 (comment)) - Cache scan results across incremental builds — currently all assemblies are rescanned every build for cross-assembly type resolution; caching the scan index or adding a two-list
Scanoverload could skip unchanged assemblies - Skip unchanged JCW files — avoid writing Java files whose content hasn't changed (attempted but read+compare cost negated savings; may be worth revisiting with content hashing)
- XDocument → XmlReader/XmlWriter for manifest generation — the manifest generator uses
System.Xml.Linq(full DOM tree); explore streaming withXmlReader/XmlWriterto reduce allocations (suggested by @jonathanpeppers in [TrimmableTypeMap] Assembly-level manifest attribute scanning #11035)
Sub-issues
Collapse Sub-issuesSub-issues
Loading 9 sub-issues
Activity
simonrozsival commentedon Mar 17, 2026
PR #10959 adds per-assembly
acw-map.{AssemblyName}.txtfiles as a side-output ofGenerateTrimmableTypeMap. When optimizing incremental builds (e.g., per-assemblyInputs/Outputsor the two-listScanoverload), the acw-map files should be included in the incrementality story:AcwMapWriter.WriteToFilealready does content comparison to avoid unnecessary timestamp updates, but skipping the write entirely (when the scan is skipped) would be even better_MergeAcwMapstarget usesInputs/Outputson the per-assembly files, so it will automatically skip if no acw-map file was touchedAdding this as a consideration item for the incremental build optimization work.
simonrozsival commentedon Mar 31, 2026
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/XmlWriterwould 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/XmlWriterapproach would require building a custom in-memory model or restructuring the merge logic into a single streaming pass.Potential approach:
XmlReader, build a lightweight custom model (just element names + attributes for dedup)XmlWriterin a single passRaised by @jonathanpeppers in #11035 (review)
simonrozsival commentedon Apr 7, 2026
Follow-up from PR #11037: we prototyped broader incremental invalidation for
_GenerateTrimmableTypeMapby 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.simonrozsival commentedon Apr 23, 2026
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:
Task 1:
GenerateTypeMapUnitInvoked once per "unit" of assemblies.
TryResolveTypeencounters a cache missTask 2:
GenerateEntryPointTypeMapInvoked once after all unit tasks complete.
_Microsoft.Android.TypeMaps.dll(entry-point assembly withTypeMapLoader.Initialize())Debug vs Release flow
Incremental builds via assembly dependency graph
For MSBuild
Inputs/Outputsto 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:
ComputeTypeMapDependenciesA lightweight pre-task reads each assembly's
AssemblyRefmetadata table (System.Reflection.Metadata, microseconds per assembly) and builds the transitive dependency graph.Pruning: only Java-peer-bearing assemblies matter
An assembly can only contain Java peer types (
[Register],[JniTypeSignature]) if it referencesMono.AndroidorJava.Interop(directly or transitively). Assemblies likeSystem.Runtime,System.Text.Json, etc. can never affect the typemap. The pre-task prunes the dependency graph by checkingAssemblyRefentries — if an assembly's transitive closure doesn't includeMono.AndroidorJava.Interop, it's excluded from the dependency set.MSBuild integration
Incrementality in practice
During typical inner-loop development:
MyApp.dll→ only_MyApp.TypeMap.dllis rebuiltMono.Android.dll,Java.Interop.dll, library DLLs are all stable → their typemap DLLs are untouchedOn SDK/NuGet update:
Mono.Android.dllchanges → all typemaps that transitively depend on it are rebuiltLazy reference assembly loading
The scanner (
JavaPeerScanner) currently callsAssemblyIndex.Createfor 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
TryResolveTypeencounters 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
ComputeTypeMapDependenciesoutput can itself be cached — only recompute when the set of input assemblies changesScope
Optimization and refactoring. No behavioral changes to the generated typemaps or runtime behavior.
simonrozsival commentedon May 25, 2026
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:
_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._GenerateTrimmableTypeMaphas target-level MSBuild incrementality viaInputs/Outputs, including references, the app assembly, manifest, and$(_AndroidBuildPropertiesCache), so no-op builds can skip the task entirely.acw-map.txt,ApplicationRegistration.java, and JCW files useCopyIf*Changed-style writes. JCW files are no longer blindly rewritten.What still needs revisiting:
GenerateTrimmableTypeMapreceives all assemblies, opens all PEReaders, eagerly buildsAssemblyIndexfor every assembly, and scans everything sequentially. There is noGenerateTypeMapUnit,GenerateEntryPointTypeMap,ComputeTypeMapDependencies, per-assembly MSBuildInputs/Outputs, or lazy reference assembly loading yet.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.CopyIfStreamChangedpreserves timestamps, but it does not avoid generation or comparison cost. Parallel generation and/or cheaper content hashing remains worth revisiting.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.acw-map.{AssemblyName}.txtfiles or_MergeAcwMapson currentmain; it currently writes one mergedacw-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.
simonrozsival commentedon May 25, 2026
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 undercaffeinate; Android still emitted onlyWaitTime, so the*startup values includeWaitTimefallback samples.Environment: .NET SDK
11.0.100-preview.5.26258.110, MSBuild18.8.0-preview-26258-110, macOS arm64 host, Samsung arm64-v8a device (R58Y30HZ65V). The test project used<TrimMode>full</TrimMode>.A few takeaways:
These numbers give us a baseline to improve against: we need to drive down both build times and startup performance. 🚀
[TrimmableTypeMap] Reuse base UCO wrappers for inherited overrides (#…
[TrimmableTypeMap] Preserve trimmable typemap outputs on no-op builds (…
jonathanpeppers commentedon Aug 12, 2026
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.
[TrimmableTypeMap] Skip redundant assembly reference scans (#12440)
[build] Avoid staging unchanged framework assemblies (#12448)
[build] Avoid archiving extracted library resources (#12447)