runtime: MAUI .NET 8.0 built with Full AOT Compilation reports a lot of `Mono : AOT NOT FOUND`

Description

When I build maui application for Android with full aot compilation, I see a lot of aot not found log messags for mono aot logger. Especially for generic class/methods. Even for the ones I expect that should be statically detected. E.g.: 04-15 18:43:11.957 28518 28518 D Mono : AOT NOT FOUND: System.Collections.Concurrent.ConcurrentDictionary`2<Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceIdentifier, Microsoft.Extensions.DependencyInjection.ServiceProvider/ServiceAccessor>:.ctor ().

04-15 18:43:23.703 28518 28518 D Mono : AOT NOT FOUND: System.Runtime.CompilerServices.AsyncTaskMethodBuilder1<System.Threading.Tasks.VoidTaskResult>:GetStateMachineBox<MauiAotTest.Components.Pages.Weather/<OnInitializedAsync>d__2> (MauiAotTest.Components.Pages.Weather/<OnInitializedAsync>d__2&,System.Threading.Tasks.Task1<System.Threading.Tasks.VoidTaskResult>&).

See attached files: one with full log for the app and the one with aot not found only messages.

LogNote_47021f4c_20240415_18.43.07_tst2_aot_full_not_found.txt LogNote_47021f4c_20240415_18.43.07_tst2_aot_full.txt

Steps to Reproduce

  1. Create a template maui blazor app
  2. Build it with AndroidEnableProfiledAot=false and install on Android device
  3. Enable mono aot logging with command adb shell setprop debug.mono.log default,timing=bare,assembly,mono_log_level=debug,mono_log_mask=aot
  4. Captute log with logcat
  5. See a lot of aot not found (exclude the ones for wrappers) log messages.

Link to public reproduction project repository

https://github.com/crui3er/MauiAotTest

Version with bug

8.0.3 GA

Is this a regression from previous behavior?

Not sure, did not test other versions

Last version that worked well

Unknown/Other

Affected platforms

Android

Affected platform versions

No response

Did you find any workaround?

No

Relevant log output

No response

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Reactions: 28
  • Comments: 136 (33 by maintainers)

Most upvoted comments

While there have been some useful observations in this very long thread, the active work in this is Android NativeAOT and there are active PRs from @jonathanpeppers which are encouraging to see. NativeAOT will fully resolve the issue of lack of full AOT while giving us a much better full AOT than Mono AOT.

The continued activity in the thread seems to be related to maui blazor specifically. It’s no surprise that maui+blazor+mono+android combo is very slow. @alexyakunin your request for updates are overly persistent and could distract the dotnet team from important tasks of more general benefit to dotnet on android. “It’s going to be 1 year from the moment this [performance issue] is reported.” This is not unusual and it also means that you had 1 year to migrate away from blazor and chose not to do so.

I completely agree with the opinion that one of the most serious and long-standing issues with Xamarin.Android is the slow startup time for applications. If you search the internet for “Xamarin.Android slow startup,” you’ll find thousands of discussions on this topic. Even with all possible optimizations, including AOT compilation, the startup time remains slow. This problem is particularly noticeable with UI frameworks such as Avalonia, UNO, and MAUI. Developers simply don’t have the ability to solve this problem on their own, as it is rooted in the fundamental aspects of the platform’s operation, and a significant amount of time is spent on JIT compilation.

When .NET Native was introduced, I thought it would be the solution to the slow startup problem for Android. Starting with version .NET 8.0, it became stable for iOS, and I began actively using it. The results are impressive: a fairly large application on an iPhone X launches as quickly as any native application and even faster than a similar application on a Samsung Galaxy S22 Ultra, despite all possible optimizations for Android. The gap between the release of these devices is five years, and I dread to imagine the startup time on a five-year-old Android device.

However, observing the discussions about .NET Native and the activity around this topic, I get the impression that the team does not give this problem enough priority, and no specific timelines have been set for its resolution. For example, in one of the discussions on GitHub, the following is mentioned:

These will likely work under Mono, but will need to be fixed one day in .NET 10 or some future release that supports NativeAOT. https://github.com/dotnet/android/issues/8724

This gives the impression that allocating resources for NativeAOT on Android is not a priority, and instead, new releases include optimizations that only provide marginal improvements (e.g., -10% startup time for test cases). However, in real-world conditions, such improvements do not solve the problem. If an application takes 2000ms to start, even reducing it to 1800ms makes little difference, and at best, such optimizations are noticeable only under ideal conditions.

It seems to me that the team does not fully grasp the depth of this issue. Many of my colleagues have already switched to Flutter specifically because of the slow startup times on Android. When their clients or customers ask why the Android application launches so slowly, developers are forced to reply that it is a limitation of the technology they are using, they may also suggest switching to iOS, where there are no such problems, but this is not an option.

In my opinion, issues like this, and especially the implementation of NativeAOT support for Android, should be considered critically important. I would like to hear the team’s thoughts on this matter: what should we expect? Will NativeAOT support for Android be added in the near future, or should we only hope for small, incremental performance improvements that don’t solve anything and are waiting for everyone to switch to Flutter?

@crui3er Thanks for providing more information about this. I will take a look at this.

There are multiple problems. I do not think we have a complete list. One of them: Java interop uses Reflection.Emit. If you configure the runtime to have no JIT and no interpreter, Reflection.Emit is going to be break and Java interop too.

why it can’t be fixed on Android

Nit: I have said that there is no simple quick way to fix it. It is all fixable in principle. For example, Java interop mentioned above can be refactored to avoid Reflection.Emit dependency and, in fact, we are looking into that.

our general plan has been “be better than we had in Xamarin”.

@jonathanpeppers sounds like you’re saying we should be thankful for what we have & patiently wait?

Not sure how to stress on this, but this isn’t a small problem. This is a crucial issue any MAUI app suffers from:

  • It severely impacts app startup time - likely, by 2-4x compared to the ideal profile-based AOT case. I shared that e.g. in our case 75% of CPU time is spent on JIT during the very first second - all due to this.
  • It elevates the ANR rate for any MAUI app that uses notifications on Android - there are tons of low-profile devices which will register ANR if your click on a notification, and the main thread is still busy 5s after that. Read about 9s of startup time in @bcaceiro case above; and we measure ~ the same numbers on ~ 3-4 years old devices.

And it hit where it hurts the most - it disproportionally impacts performance-critical code right during the startup.

If an application takes 2000ms to start, even reducing it to 1800ms makes little difference

I’ve found simply profiling your app (with dotnet-trace) and improving things, you should be able to get this quite a bit shorter. If you’ve already recorded a custom AOT profile, or already “AOT everything”, what is left is to profile your own code. In the customers I’ve helped in the past, we’ve always been able to achieve reasonable results on a mid-range device.

I am actually curious… What’s the largest app on MAUI + Blazor that’s built at Microsoft? Are there any at all?

Sorry for a bit angry response, but you guys kinda underestimate the amount of efforts some of us have to invest to improve startup time, as well as our level of experience. I’ll list just some of things we already did:

  • All service registrations are replaced w/ delegate-based ones
  • So every client-side service is resolved either explicitly, or via an intermediate service caching hub like this one: https://github.com/Actual-Chat/actual-chat/blob/dev/src/dotnet/UI.Blazor.App/Services/ChatUIHub.cs
  • Custom service container that allows us to start some services (mostly related to web view) early while registering the rest (this saves 50-100ms on startup).
  • Use of MemoryPack everywhere (it’s a serializer with Roslyn code generator, so no runtime codegen)
  • Similarly, all our proxies are also generated in compile time
  • Profiling & postponing everything that takes time @ startup or moving it to parallel threads.
  • Warming up whatever runs on later startup stages earlier in a concurrent thread - actually this doesn’t help much, seemingly b/c JIT concurrency is limited, and it’s all about these AOT_NOT_FOUND
  • Getting rid of key generic use cases. E.g. our proxies were heavily using ArgumentList<T0,T1,...> type to capture method call arguments with just one allocation (contrary to object[] used by nearly any other proxy generator), and I ended up adding an “array mode” for this abstraction to get rid of generics & make it more AOT-friendly: https://github.com/ActualLab/Fusion/commit/1e12033613fea420febbdf58d7c247e948ee7d4e
  • Identifying and creating this issue, which is a key bottleneck in our case now.

But in the end, we can do only so much - e.g. we can’t really change:

  • The code involving AsyncTaskMethodBuilder<T> & similar types (i.e. async code)
  • ConcurrentDictionary.GetOrAdd(key, static (key, state) => ..., state) scenarios
  • Most of cases involving Fusion’s Computed<T> abstraction.

As for NativeAOT, I’ve made a simple test to see how far we’re from being able to use it, and it just confirmed my worst thoughts:

All in all, I think you guys make a HUGE mistake:

  1. There are generics, Span<T> & tons of other types which makes .NET blazingly fast on the server side. I’m a big fan of .NET partially due to its perf.: https://itnext.io/geting-4x-speedup-with-net-core-3-0-simd-intrinsics-5c9c31c47991 (it’s my post)
  2. You claim .NET code is 100% portable / runs everywhere - and it does. But features like generics and Span<T>, which are supposed to make it fast, are also mobile startup performance killers.
  3. And it’s all due to the fact Mono AOT is incapable of generating generic method instances we really need.
  4. Native AOT w/o universal shared generics also doesn’t look promising - unless you guys add some tooling allowing to e.g. programmatically enumerate possible generic parameters for certain types & methods right during the link stage. E.g. in our case we technically can do this, but it will require a decent amount of work. As you might guess, it’s totally unacceptable for any real app to fail at a random point just because one of generic methods doesn’t have an AOT version.

So IMO you need to address this issue. And @vyacheslav-volkov is absolutely right: there is a ton of critics of MAUI itself, but MAUI app startup time is a key issue faced by people like us - i.e. the ones who made it through all the hoops. The ones who found fixes or workarounds for everything else people complain about.

@charlesroddie my thoughts are:

  • Yes, we obviously still consider migration. Not sure how (not) smart you are, but it’s not a piece of cake for any large project, esp. taking into account the only reason for doing that is 2-second startup time.
  • “It’s no surprise that maui+blazor+mono+android combo is very slow.” - not surprising for whom, sorry? For the sake of clarity, did I ever mentioned it is slow in general? Or “very slow”?
  • I certainly welcome NativeAOT, but it’s not an excuse for ignoring this issue in Mono/MAUI. If you read other posts on NativeAOT timeline for Android, “somewhere in 2026” would be an optimistic estimate.

As for “you had 1 year to migrate away from Blazor and chose not to do so”, it’s the dumbest thing I read here. To clarify, it took about 6 months to get the “ok, we tried something, it didn’t help, the rest seems complex / we probably don’t understand how to fix it, coz Mono isn’t really ours” kind of answer from Microsoft here.

P.S. IDK who is @charlesroddie , but if he’s an MS employee, maybe it makes sense to either clearly write what he just stated on every MAUI page, or… Provide a better answer and explain the basics of customer communication to @charlesroddie .

cc @steveisok @vitek-karas

Mono AOT compiler has number of limitations as you have found. I doubt that there is a simple quick way to address them in the existing releases. I am sorry. We have been discussing these topics among ourselves and how to address the issues like the one you have reported going forward. We will share our goals for .NET 10 once we have firm plans in place like we have done for past releases (likely after the New Year for this area).

@vyacheslav-volkov just want to say I fully agree with this:

It seems to me that the team does not fully grasp the depth of this issue. Many of my colleagues have already switched to Flutter specifically because of the slow startup times on Android. When their clients or customers ask why the Android application launches so slowly, developers are forced to reply that it is a limitation of the technology they are using, […]

I can add that maybe up to 95% of developers simply won’t dig that far to identify this specific issue. Most of them have no time for this, and only a fraction of the remaining ones has the experience needed to figure out what’s going on.

That’s why only a few people complaining here. But the fact others don’t even bother to dig is actually a very negative thing for Microsoft, because their conclusion is much simpler: MAUI is intrinsically slow. We’ve invested a lot to build a product on it, and now the only thing we can do is to switch to Flutter or some other alternative. + Lesson learned: trusting Microsoft was a mistake.

And from the business perspective this is the only conclusion you can make. The explanation doesn’t really matter while the underlying issue isn’t fixed.

Any news? A couple more months and it’s going to be 1 year from the moment this bug is reported.

I have an experiment here that shows how to use BlazorWebView without MAUI:

It has comparisons of app size and startup time with MAUI+Blazor.

I did have to bring in some of the BlazorWebView source for it to work – I think just minor changes, though.

If you are wanting the absolute fastest WebView experience, it seems like you could use a standard dotnet new android project with a WebView and not use MAUI. MAUI+Blazor is like including the entire .NET “kitchen sink” in your app.

To be honest, if you are looking for speed, maybe native controls are the way to go instead of web content?

P.S. The conversation is getting a bit heated… Can we try to refocus it on how to solve this specific issue / why it’s complex? I’d love to know why these specific constraints exist, and what specifically prevents Microsoft from making them much less restrictive.

This comment also worth reading: https://github.com/dotnet/runtime/issues/106748#issuecomment-2325985567 and a few more following it. A brief summary: if this fix is complex, and it’s needed only for Android, how it’s possible that the very same Mono AOT generates the code for all generic instances for iOS?

Separately, this should only ever happen if you’re using reflection…

I don’t understand why banning devs from using what’s quite convenient is viewed as an acceptable trade-off here.

The way I would approach this is: if reflection is a mistake, we should try removing it from .NET. And if it’s a genuinely useful thing (that’s what 90+% of developers will tell you), we should stop pretending it’s ok to break it in AOT builds only.

In a low end device - for example, a Zebra Phone ( corporate), I have startups of 9 seconds, which is far from acceptable, and I have no external dependencies, or packages, and try to minimize the work during the startup (only .net maui, skiasharp and sentry),

@bcaceiro a few recommendations:

  1. Try removing Sentry. If you use their recommended way of plugging it in, it alone eats up maybe 2 seconds in your case. At least that’s what we saw with its default setup.
  2. Try running the same exercise - i.e. enable mono logging & count how many “AOT NOT FOUND” you see with full vs profile-based AOT. Let’s team up to cry more loudly about this 😦

Personally I don’t understand how it even makes sense to compare the MAUI/Mono AOT vs Native AOT assuming Mono-based AOT is broken to such an extent.

Looked a little bit into the sample application. For the template application, about 5759 methods are loaded from AOT while 1578 are not found (21.5% methods jitted). It seems like the biggest culprit is generic methods with valuetype arguments. Hacking the runtime/build a little bit to enable gsharedvt resulted in 3680 method loaded from AOT, with 557 methods jitted (13% methods jitted), however the runtime crashed at this point. It seems that enabling gsharedvt on android could work and could result in good startup improvements however it is a configuration that was not really supported outside of full-aot configurations so it has some issues. It is not yet clear how challenging it would be to fix them, it would require further investigation.

@alexyakunin Please do not fall for this provoc, this guy is anything but MSFT, suggesting everyone to “work out the cost of porting to uno or avalonia” and now “migrate away from blazor”.

I tried using “full AOT” with interpreter fallback here, just to see if it can work:

But the AOT compiler hits an assert on Windows. It’s possible this will run on macOS, as they mentioned the AOT compiler might just have some preprocessor to drop the interpreter on Windows.

Let me add a macOS-only test to see how it goes.

Using “full AOT” with no interpreter fallback fails in a different way:

Okey, so .NET 9 is released (I hope that explains why no one could help earlier), any chance someone looks at this now?

@alexyakunin would you be interested in a CoreCLR/NativeAOT-based “launcher” for Blazor?

We have a prototype of an Android backend for Avalonia that could be repurposed to host a WebView.

You can see the difference of running the same Avalonia-based app using CoreCLR+NativeAOT, ~xamarin~ maui-android mono with our custom interop and using full ~xamarin~ maui-android interop.

Any update Microsoft, this is a rather big issue, apps take many many seconds to load on Android.

P.S. The conversation is getting a bit heated… Can we try to refocus it on how to solve this specific issue / why it’s complex? I’d love to know why these specific constraints exist, and what specifically prevents Microsoft from making them much less restrictive.

This comment also worth reading: #106748 (comment) and a few more following it. A brief summary: if this fix is complex, and it’s needed only for Android, how it’s possible that the very same Mono AOT generates the code for all generic instances for iOS?

To be brutally honest, this will only quick change if and when Google ban VM from running on it’s platform. Just look at Apple, you either comply or take your game elsewhere.

@alexyakunin

One quick question - what is DynamicallyAccessedTypes.DynamicMemberInfo? I.e. is it a mistake or some mix of flags?

Yes, you can define the flags you need for the type, in my case they are construct flags:

public const DynamicallyAccessedMemberTypes DynamicMemberInfo = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors;

Also, LinkerIncludeGenericType is non-generic - it’s to prevent AOT from generating useless method instances?

Yes, there’s no point in making it generic since you can just pass the type.

Hi @jonathanpeppers, yes, I do all of this in my applications, and yet the iPhone X with NativeAOT still performs faster than the Galaxy S22 Ultra. Additionally, to go through all these steps, you need to use various scripts and possess additional knowledge on how to use and set everything up, whereas, for example, Flutter offers a convenient profiler built into the environment that requires no extra knowledge.

In the end, to write a “fast application” for Android that still lags behind native applications in terms of startup speed, you need to perform a whole range of additional operations, which not every developer can manage, just to make their application work somewhat faster. I believe that this expectation is where the main problem lies. A developer expects that the release build will immediately work as it should, but instead, they encounter performance issues where they don’t expect them.

NativeAOT could be the solution to this problem. Yes, there are still limitations on using dynamic code, but they are not that difficult to overcome, resulting in an application that performs as fast as a native one. Isn’t that what we want for a cross-platform application? Moreover, I’m almost 100% sure that no one uses Android applications without ProfiledAOT or FullAOT because, in that case, you can forget about startup performance. This also means they are already using trimming, so transitioning to NativeAOT wouldn’t require much additional effort. Over time, more libraries and frameworks will become fully compatible with NativeAOT, making integration seamless for developers without any issues.

By the way, the folks from the Avalonia team used NativeAOT for Android and compared performance here. The video speaks for itself—this is what every developer expects from their application’s startup speed.

I’ve had an excellent experience using NativeAOT on iOS, and the result is that the application runs almost as if it were written in Swift/ObjectiveC. Because of this, I’m very interested in understanding the Android team’s thoughts on NativeAOT and why it appears to have such a low priority. When developing cross-platform applications, we rely on a shared codebase, so for developers targeting both iOS and Android, it wouldn’t make much difference if Android didn’t support dynamic code—after all, iOS doesn’t support it either.

And we assume that it is more common for the generic type to be a reference type during runtime

If you mean generic type parameters, it’s a false assumption. On contrary, tons of optimizations on .NET are crafted in assumption a specific version of code is generated for such generic methods.

It’s quite sad you don’t see this fixed in .NET 9 - it means profile-based AOT will stay mostly broken on MAUI. If you see 800+ JITted calls on toy apps, imagine how bad it is in non-toy ones. If 80+% of your startup time is wasted on JIT, claiming that profile-based AOT is there is like… Giving soldier a floating vest and claiming it’s bulletproof.

@jonathanpeppers maybe you want to add something. IMO it’s literally a case when the feature is broken so badly it effectively doesn’t exist.

We’ll share more details on our specific stats later, but I am absolutely sure we aren’t unique in this sense.

Just checked out the comments to PR - thanks for working on this! Looking forward to seeing more (or most) of these cases are closed!

Yeah, and as @crui3er noted, this means that async state machines aren’t AOT-compiled. And this alone is a huge deal for any moderately complex app.

Are you able to share a .nettrace or .speedscope file of startup? There might be something we can fix in .NET MAUI or recommend.

We’ll do this. Do you need a .nettrace file for full AOT or profile-based AOT? I am also not fully sure if .nettrace collection interacts with any other options, so if you can list some build options we definitely need to enable while collecting the trace, it would be great, @jonathanpeppers

Also, on MAUI itself - I guess what would be great is to have a “MAUI-less” version of Blazor Hybrid, or at least have a mode there which registers only what’s needed for Blazor Hybrid apps. We don’t use any MAUI controls except Window & WebView, so e.g. RemapForControls call you see on the screenshot above takes 65ms, though in reality at least a half of controls registered there aren’t used.

And unrelated, but: we spent a decent amount of time trying to enable AOT for iOS at least for some assemblies, but this inevitably leads to crashes. That’s why for now the app works in interpreter mode there.

@alexyakunin Feel free to open an issue for the crash you’ve seen.

I was able to build and run the app provided here. When setting AndroidEnableProfiledAot=true and enabling logging. I could see the 2/3 example @crui3er provided earlier, for example 1, they are not the same method.

I also noticed that this profile was gathered using the legacy profiler. Next, I will try the new profiler to see if this issue still exists. If so, I will investigate further.

Hi there, just curious, are there any updates on that?

I want to add some context: the app we’re working on shows ~20K methods in “AOT NOT FOUND” log entries - and that’s just for the startup time. We were questioning whether AOT is even working at all - well, it does, coz there are also lots of “AOT FOUND” entries, but it’s reasonable to assume that if you have even 50/50 split between these, you’re probably getting just 50% of max. possible savings on JIT. And with AOT turned off, our startup time is almost 2x higher. In other words, if AOT issues would be fixed, our app’s startup time would go from ~ 1.7s to probably just 0.3-0.5s or so, which is obviously a dramatic change.

Please let @crui3er know if you need anything else. We can provide logs from the actual app + give you instructions on how to reproduce the issue there, if a small sample won’t be enough to identify the root cause(s).

And IMO it’s super important to address this: compared to Native AOT, profile-based AOT (assuming it 100% works) is what most of mobile apps need. It allows to balance between the app size and the speed of the most crucial parts of the app, which is almost always the startup time for mobile apps. So nearly any MAUI and Blazor Hybrid app would benefit from this heavily.