Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[android] improve ToolbarExtensions.UpdateIconColor performance (#17241)
I've been working to get back some of our lost startup performance on Android in .NET MAUI. We are really close, a few changes will get .NET 8 on par or faster than .NET 7. Profiling startup of a `dotnet new maui` app on a Pixel 5, `dotnet-trace` reported time spent in: 16.62ms microsoft.maui.controls!Microsoft.Maui.Controls.Platform.ToolbarExtensions.UpdateIconColor( If you drill in further in this method, you can see the time spent in: 10.19ms xamarin.androidx.appcompat!AndroidX.AppCompat.Widget.Toolbar.get_OverflowIcon() 6.42ms microsoft.maui!Microsoft.Maui.Platform.DrawableExtensions.SetColorFilter() The project template doesn't even display a `Toolbar` icon, but it looks like there are some straightforward performance wins here. In 9b091fd, accessing `OverflowIcon` was introduced to fix the color of the overflow icon. This code had the pattern: if (navIconColor != null && nativeToolbar.OverflowIcon != null) { nativeToolbar.OverflowIcon.SetColorFilter(navIconColor, FilterMode.SrcAtop); } This accesses `OverflowIcon` twice, where we can use pattern matching instead to avoid this. Additionally, `SetColorFilter` appears to be called in a couple places throughout .NET MAUI, we can move most of its logic to Java to avoid interop. So for example: switch (mode) { case FilterMode.SrcIn: return BlendMode.SrcIn; case FilterMode.Multiply: return BlendMode.Multiply; case FilterMode.SrcAtop: return BlendMode.SrcAtop; } `Enum` values are just classes in Java, so this calling a Java method from C# that returns an object. We then have to do various bookkeeping around handling this Java object instance in C#. Then the other call, also does Java interop for `BlendModeColorFilter`'s constructor and the `SetColorFilter()`: drawable.SetColorFilter(new BlendModeColorFilter(color, filterMode29)); By moving this logic to Java, we can instead call: PlatformInterop.SetColorFilter(drawable, color, (int)mode); We also do the API Q/29 platform checks on the Java side. With these changes in place, the three methods above are improved: 6.19ms microsoft.maui.controls!Microsoft.Maui.Controls.Platform.ToolbarExtensions.UpdateIconColor() 3.87ms xamarin.androidx.appcompat!AndroidX.AppCompat.Widget.Toolbar.get_OverflowIcon() 1.15ms microsoft.maui!Microsoft.Maui.Platform.DrawableExtensions.SetColorFilter() I would estimate these changes improve startup by about ~10ms on a Pixel 5, seeing the savings on the topmost method, `UpdateIconColor()`.
- Loading branch information