Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 42 ยท Testing and Publishing

Performance and Startup

Make .NET MAUI apps start fast and scroll smoothly: lazy loading, compiled bindings, virtualized lists, image sizing, trimming, AOT and measuring with simple timers and profilers.

Users judge an app in the first two seconds and keep judging it every time they scroll. Performance in MAUI comes from a few habits: do less at startup, keep the UI thread free, show only what is visible, and measure before you optimize. This lesson turns those into concrete techniques.

The device tools (profilers, build properties) are explained read-only. The runnable stand-ins measure the effect of caching, lazy initialization and virtualization-style paging in plain C#. Timing numbers differ per machine, so the examples print counts and ratios you can rely on.

Measure first

Guessing wastes time. Tools to know:

  • A Stopwatch around suspicious code for quick checks.
  • dotnet-trace and dotnet-counters for CPU and memory of a running device app (Android over adb, iOS via a tunnel).
  • Android Studio Profiler and Xcode Instruments for native memory, frame rate and energy.
  • Visual Studio's performance profiler for Windows builds.
  • Always measure a Release build on a real, modest device. Debug builds, emulators and flagship phones tell you little.
C#
var sw = Stopwatch.StartNew();
await LoadDataAsync();
logger.LogInformation("Load took {Ms} ms", sw.ElapsedMilliseconds);

Startup

Startup has several phases: the OS launches the process, the .NET runtime starts, MauiProgram.CreateMauiApp builds the host, then the first page is created and rendered. You control the last two.

Keep CreateMauiApp small

Everything you register runs before the first pixel. Do not open databases, call the network, or read large files there. Register services as lazy singletons and let them initialize on first use:

C#
builder.Services.AddSingleton<IAppDatabase, AppDatabase>();   // constructed on first request, not now

Inside the service, delay work until the first call:

C#
public class AppDatabase
{
    private SQLiteAsyncConnection? _db;

    private async Task InitAsync()
    {
        if (_db is not null) return;
        _db = new SQLiteAsyncConnection(Path);
        await _db.CreateTableAsync<Note>();
    }

    public async Task<List<Note>> GetNotesAsync()
    {
        await InitAsync();
        return await _db!.Table<Note>().ToListAsync();
    }
}
C# Stand-in: lazy initialization vs eager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first page

  • Show something immediately (a skeleton or the cached last state), then load fresh data in the background.
  • Do not call Wait() or .Result on tasks: it blocks the UI thread and can deadlock.
  • Avoid deeply nested layouts and huge XAML on the first page.
  • A splash screen is a placeholder, not a loading screen. Keep the time to the first page under a second where possible.

Build-time settings

For Release builds, these project settings reduce startup and size:

XML
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
    <PublishTrimmed>true</PublishTrimmed>           <!-- remove unused code -->
    <TrimMode>partial</TrimMode>
</PropertyGroup>
  • Trimming removes code nothing references. Reflection-heavy libraries (some JSON serializers) can break; use source-generated System.Text.Json contexts and test the Release build.
  • AOT (ahead-of-time compile, always on for iOS) turns IL into native code at build time, improving startup at the cost of bigger packages. On Android, AndroidEnableProfiledAot (the default for Release) precompiles hot startup paths.
  • XAML compilation (XamlCompilation is the default now) validates and compiles XAML to IL.

Rendering and layouts

Every layout pass measures and arranges the tree. Keep it cheap:

Do Avoid
A single Grid with rows and columns Deep StackLayout inside StackLayout nesting
Fixed or Auto rows when possible Many * rows with nested content
CollectionView for lists ScrollView + VerticalStackLayout with hundreds of children
IsVisible="False" for large hidden pages Creating hidden controls just in case
Animating TranslationX and Opacity Animating WidthRequest

ListView is legacy; CollectionView virtualizes: it creates controls only for the rows on screen and recycles them while scrolling. The cell template should be simple, because it is created many times.

Lists: paging and virtualization

A list of 50,000 items should not load 50,000 items. Load a page at a time when the user nears the end (RemainingItemsThreshold, RemainingItemsThresholdReachedCommand), and keep per-row work (formatting, image decoding) out of the template:

XML
<CollectionView ItemsSource="{Binding Items}"
                RemainingItemsThreshold="5"
                RemainingItemsThresholdReachedCommand="{Binding LoadMoreCommand}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:Photo">
            <Grid ColumnDefinitions="64,*" Padding="8">
                <Image Source="{Binding ThumbnailUrl}" WidthRequest="64" HeightRequest="64" />
                <Label Grid.Column="1" Text="{Binding Title}" LineBreakMode="TailTruncation" />
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

The pattern in code is a simple page cursor:

C# Stand-in: paging a big list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Keep the UI thread free

Anything over about 16 ms in a UI callback drops a frame at 60 Hz. Move heavy work to the background and hop back only to update controls:

C#
var result = await Task.Run(() => ParseLargeFile(path));   // background
Items = new ObservableCollection<Item>(result);            // back on the UI thread after await

Further rules:

  • Use async I/O (HttpClient, File.ReadAllTextAsync, SQLite async APIs).
  • Add many items with one replacement, not 1000 Add calls that each notify the UI.
  • Debounce search boxes: wait 300 ms after the last keystroke before querying.
C# Stand-in: caching an expensive call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Memory

  • Unsubscribe from events (+= without -= keeps objects alive, a classic leak), especially static events and long-lived services. Prefer WeakReferenceMessenger from the MVVM Toolkit for messaging.
  • Dispose streams, HttpResponseMessage, Stream-based images and CancellationTokenSource.
  • Decode images at the size you show (see Fonts, Images and Icons).
  • Pages in a navigation stack stay alive; clear heavy data in OnDisappearing or when popped.
  • Reuse one HttpClient (inject IHttpClientFactory), never create one per request.

A performance checklist

  1. Test a Release build on a mid-range device.
  2. Keep CreateMauiApp light; initialize services lazily.
  3. Use compiled bindings, CollectionView, shallow layouts.
  4. Load data asynchronously; show cached or placeholder content first.
  5. Thumbnails in lists, full images only on demand.
  6. Trim and test; measure again after each change.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should heavy initialization such as opening a database happen?

    Work done in CreateMauiApp delays the first page. Lazy initialization pays the cost only when the feature is used.
  2. 2. What makes CollectionView efficient with very long lists?

    Virtualization creates only the rows visible on screen, so the cost does not grow with the list size.
  3. 3. Which animation target is expensive?

    Changing a size forces a layout pass on every frame; transforms and opacity do not.
  4. 4. What is a common cause of memory leaks in MAUI apps?

    An event subscription keeps the subscriber reachable from the publisher, so pages and view models are never garbage collected.

Summary

  • Measure Release builds on real devices before optimizing.
  • Keep startup light: lazy services, quick first page, trimming and AOT in Release.
  • Use compiled bindings, shallow layouts and CollectionView with paging.
  • Do heavy work off the UI thread; cache expensive results.
  • Prevent leaks: unsubscribe, dispose, size images correctly.

Next: Publishing to the Stores