Introduction
Performance is critical for delivering smooth, responsive apps across devices. This tutorial covers techniques to measure, analyze, and improve your .NET MAUI application's speed and memory footprint.
Measuring Performance
Use the built‑in Stopwatch for quick benchmarks and Microsoft.Maui.Graphics for rendering metrics.
using System.Diagnostics;
public static long Measure(Action action)
{
var sw = Stopwatch.StartNew();
action();
sw.Stop();
return sw.ElapsedMilliseconds;
}
// Example
long ms = Measure(() => LoadHeavyData());
Console.WriteLine($"Load took {ms} ms");
Reducing Memory Usage
Prefer ValueTask over Task for lightweight async, and recycle SKBitmap instances.
public async ValueTask<string> GetDataAsync()
{
// implementation
}
// Reusing bitmaps
var bitmap = new SKBitmap(width, height);
using var canvas = new SKCanvas(bitmap);
// draw...
Optimizing UI Rendering
Leverage Layout optimizations, avoid excessive bindings, and use Compiled Bindings where possible.
- Set
CacheLengthonCollectionViewto reduce off‑screen layout. - Use
GraphicsViewfor custom drawing with minimal overhead.
Profiling Tools
Visual Studio Diagnostic Tools, dotMemory, and the MAUI Profiler extension help identify bottlenecks.
| Tool | Focus | Link |
|---|---|---|
| Visual Studio Profiler | CPU & Memory | Docs |
| dotMemory | Memory Snapshots | Site |
| MAUI Profiler | Layout & Render | Tutorial |
Best Practices
- Minimize layout passes – use
Gridwith fixed rows/columns where possible. - Prefer
ObservableCollection<T>withBatchUpdatesfor large data sets. - Avoid heavy work on the UI thread – offload to
Task.RunorBackgroundWorker. - Enable
Releasebuild optimizations before publishing.
FAQ
How do I detect UI thread lag?
Use Device.StartTimer to schedule a small interval and compare actual vs. expected times.
What is the impact of XAML compilation?
Enabling XAML compilation ([XamlCompilation(XamlCompilationOptions.Compile)]) reduces load time and memory usage.