dotnet / android

.NET for Android provides open-source bindings of the Android SDK for use with .NET managed languages such as C#
MIT License
1.93k stars 532 forks source link

Use precompiled DEX files to speed builds #9534

Open jpobst opened 1 day ago

jpobst commented 1 day ago

Our _CompileToDalvik task is currently the most expensive part of a user application build.

For example, for the following sample:

dotnet new android
dotnet add package Xamarin.AndroidX.Activity --version 1.9.3.1

This passes 34 dependency .jars to the _CompileToDalvik task, which takes ~11.5s to execute on a DevBox.

D8 provides the ability to compile a library individually ahead of time. When the "final" compilation is done it only needs to copy over the DEX code rather than compile it.

android-toolchain\jdk-17\bin\java.exe
  -Xmx1G
  -classpath "C:\Program Files\dotnet\packs\Microsoft.Android.Sdk.Windows\35.0.7\tools\r8.jar"
  com.android.tools.r8.D8
  --debug
  --min-api 24
  --output "mono.android.24.dex"
  "C:\Program Files\dotnet\packs\Microsoft.Android.Ref.35\35.0.7\ref\net9.0\mono.android.jar"

Precompiling the 34 dependency .jars and using them reduces the "final" _CompileToDalvik invocation to ~5.2s. 🎉

Wrinkles

The biggest wrinkle to this is that the output is different based on the --min-sdk that is passed in (particularly around desugaring), so we can't have a single precompiled DEX file. In theory we would need one per possible min-sdk, unless we can prove that we only need ones for API-21 and API-24. This makes it harder to ship precompiled binaries if we need to ship ~14 API levels.

Ideally, we could simply perform this compilation on first use and cache it, however it takes an extensive amount of time to precompile each .jar file. It takes about ~88s to precompile the 34 dependency .jars used in the test above. This is a considerably longer "first compile" than not using caching at all.