Performance & Optimisation
Android Development with Compose: Production & Publishing
Course 6 ยท Chapter 6 ยท Fast Enough, Proved
"Make it faster" without a measurement is guessing. Android Development with Compose: Production & Publishing 1 already quoted the docs: do not judge performance by recomposition counts alone. This chapter is the other half: the tools that tell you what is actually slow, the two failures users notice most (freezes and crashes from running out of memory), and baseline profiles, the biggest free startup win.
ReportDrawn, ReportDrawnWhen and ReportDrawnAfter; jank is measured with FrameTimingMetric on a LazyColumn, with testTagAsResourceId enabled so UI Automator can find Compose elements; the docs list AGP 8.0.0, Macrobenchmark 1.5.0 and ProfileInstaller 1.4.1 as requirements (versions as the docs showed them: check the current ones); the target must be profileable and include ProfileInstaller 1.3 or later; Macrobenchmark is recommended for measuring because it repeats runs; startup is compared with StartupTimingMetric and CompilationMode (one docs example: 229.0 ms with a baseline profile against 324.8 ms without compilation); generating on a Gradle Managed Device needs an aosp image, though newer releases allow Android 13+ without root; Compose composition tracing can be enabled with androidx.benchmark.fullTracing.enable, and tracing during cold start distorts timing.
Android vitals: the vitals dashboard shows stack traces for field ANRs with suggested fixes; the core vitals include crash rate, ANR rate, excessive battery use and excessive partial wake locks.
ANRs and StrictMode: an ANR is triggered when the UI thread is blocked for too long; common causes are slow I/O, long calculations and synchronous binder calls on the main thread; keep disk and network work off the main thread; StrictMode has a ThreadPolicy (one thread) and a VmPolicy (the whole process), built with detectAll(); the VmPolicy has detectActivityLeaks() and related leak detectors; enable StrictMode only on debug builds, with a crashing penalty if you want violations hard to miss.
Memory: capture a heap dump from the Profiler tab; recent Android Studio releases include a LeakCanary profiler task; Android Studio can open only heap dumps captured by its own Memory Profiler.
Not found: the exact ANR timeout (the results did not state the figure, so none is given here), and the Profiler's CPU and frame views. General knowledge, not checked: everything labelled so below. All code is unrun (no Kotlin compiler on the machine used to write this); nothing was seen on your install.
The Rule: Measure, Change One Thing, Measure Again
| Symptom | First tool |
|---|---|
| Slow to start | Macrobenchmark StartupTimingMetric (docs), then a baseline profile |
| Janky scrolling | Macrobenchmark FrameTimingMetric (docs); trace file in Android Studio |
| Freezes ("not responding") | StrictMode in debug (docs); vitals ANR traces in production (docs) |
| Memory grows, then crashes | Profiler heap dump (docs), leak detectors |
| Recomposing too much | Chapter 1's checks; composition tracing (docs) |
(general knowledge) Measure on a release-like build on a real device where you can: a debug build, an emulator on a fast laptop and the R8-optimised release build (Android Development with Compose: Production & Publishing 5) can differ a lot. The docs say the target must be profileable for Macrobenchmark.
Freezes and ANRs
- (docs) An ANR happens when the UI thread is blocked for too long. Slow I/O, long calculations and synchronous binder calls on the main thread are the usual causes. (The exact timeout was not in the search results; check the ANR page for the current figures.)
- (docs) The fix is structural: keep disk and network work off the main thread. The notes app already does this by design: Room's suspend functions and Flow, the repository with
withContext, Retrofit's suspend calls.
- (docs)
ThreadPolicywatches one thread (the one you set it on),VmPolicywatches the process.detectAll()turns on every thread check. - (docs) Enable StrictMode on debug builds only. (general knowledge)
penaltyLog()writes a Logcat line;penaltyDeath()crashes the app, loud but effective on a small project. - (docs) In production, the vitals dashboard shows ANR stack traces from real users.
Memory Leaks
(general knowledge) A leak is an object that is no longer needed but is still reachable, so it cannot be collected. In Android the typical case is a long-lived object (a singleton, a static field) holding an Activity.
- (docs)
VmPolicy.detectActivityLeaks()is the StrictMode check for exactly this. - (docs) Take a heap dump from the Profiler: you can see which objects exist and what holds them. Android Studio opens only its own Memory Profiler dumps.
- (docs) Recent Android Studio versions include a LeakCanary profiler task that analyses leaks inside the IDE. (general knowledge) LeakCanary is also a library you can add to debug builds; the search did not cover its setup, so check its own docs.
- (general knowledge) A ViewModel does not leak the screen unless you hand it a Context or a view; that is the reason the ViewModel Chapter of the previous course told you not to.
Baseline Profiles
(docs) Android compiles app code as needed, so the first run is slower. A baseline profile lists the classes and methods your users hit most, so they are compiled ahead of time. Compose gains a lot because its library code is otherwise warmed up on first use.
- (docs) Set up with the Baseline Profile module template in Android Studio (or the Macrobenchmark template and the Baseline Profile Gradle plugin). Generation is a test that walks critical journeys; the plugin turns the result into a profile in your app.
- (docs) The comparison test above uses
StartupTimingMetricandCompilationMode. A docs example showed 229.0 ms with a baseline profile and 324.8 ms with no compilation: an illustration of the method, not a promise for your app. Measure yours. - (docs)
ReportDrawnWhentells the system when the screen is really usable, so startup measures the right point. - (docs) The docs also say to test a custom profile to confirm it helps, and to make sure ProfileInstaller 1.3 or later is in the target app.
- (docs) Generating on a Gradle Managed Device needs an
aospimage; newer releases allow Android 13+ without root. Check the current page for your setup. - (general knowledge, not checked) Include the profile in the release build; it is delivered to users with the app (check the Play delivery details in the docs).
Compose-Specific Performance, Revisited
- From Chapter 1: defer state reads with lambda modifiers, keep lazy-list keys stable, do not rely on recomposition counts alone (docs).
- (docs) Composition tracing can be turned on in a Macrobenchmark with
androidx.benchmark.fullTracing.enable, with a warning that tracing during cold start distorts the timing, so use it to find what is slow, and the untraced run to measure how slow.
Fixing Order
- Turn on R8 and measure again (Chapter 5; general knowledge about how big the win usually is: check on your app).
- Run StrictMode in debug and fix what it reports.
- Add a baseline profile and compare start-up.
- Only then look at individual composables, and only the ones a trace points at.
Try It Yourself
Add the StrictMode block to the debug build and use the app normally. Report every violation it logs (it will probably find something). For each, say what it is and fix one.
๐ View solutionCreate the leak from the chapter on purpose, rotate the screen a few times, take a heap dump in the Profiler and find the leaked Activity. Then fix it and repeat. Report how many Activity instances you saw before and after.
๐ View solutionAdd a Macrobenchmark module with the template, run the two startup tests on a real device if you can, then generate a baseline profile and rerun. Report the numbers and the device, and say whether the profile helped. Do not assume the docs' figures apply.
๐ View solutionReportDrawn and friends; FrameTimingMetric and testTagAsResourceId; the version requirements as shown; profileable targets and ProfileInstaller; StartupTimingMetric and CompilationMode with the quoted example numbers; Gradle Managed Device notes; composition tracing and its caveat; the vitals ANR dashboard; the ANR causes; StrictMode thread and VM policies and detectActivityLeaks(); debug-only use; heap dumps and the LeakCanary profiler task.General knowledge, not checked: what a leak is and the long-lived-object example; the leaky code as written;
penaltyLog and penaltyDeath; "measure on a release-like build"; the explanation of why Compose benefits from profiles and ahead-of-time compilation; shipping the profile in the release build; the fixing order; the ViewModel remark; every import and the code as written.Not verified: the ANR timeout figures; the Profiler's CPU and frame views; LeakCanary's own setup; the current library versions; every listing and solution (unrun); the exercises (not run by me). Nothing was checked on your install, and the docs' startup numbers are not yours.
Sources: Baseline Profiles overview (developer.android.com), Create Baseline Profiles (developer.android.com), Use a baseline profile, Compose (developer.android.com), Write a Macrobenchmark (developer.android.com), Macrobenchmark instrumentation arguments (developer.android.com), Diagnose and fix ANRs (developer.android.com), StrictMode API reference (developer.android.com), App startup analysis and optimization (developer.android.com).