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.

What was checked, and how: read this first
Checked in the docs (three searches, summaries only): Baseline profiles and Macrobenchmark: for Compose apps Google recommends a Macrobenchmark-based baseline profile covering critical user journeys, and says to test that a custom profile helps; the current setup is the Baseline Profile module template, or the Macrobenchmark template with the Baseline Profile Gradle plugin; profiles can cover scrolling, animation and navigation, not only startup; Compose screens signal when fully drawn with 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

SymptomFirst tool
Slow to startMacrobenchmark StartupTimingMetric (docs), then a baseline profile
Janky scrollingMacrobenchmark FrameTimingMetric (docs); trace file in Android Studio
Freezes ("not responding")StrictMode in debug (docs); vitals ANR traces in production (docs)
Memory grows, then crashesProfiler heap dump (docs), leak detectors
Recomposing too muchChapter 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.
// Main-safe by construction (Architecture & Data 3): the repository switches threads itself class DefaultNotesRepository( private val dao: NoteDao, private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO ) { suspend fun exportAll(): String = withContext(ioDispatcher) { // heavy file/JSON work: never on the main thread buildExportText(dao.getAll()) } }
// NotesApplication.onCreate(): catch accidental main-thread work and leaks in DEBUG builds only if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() // docs suggest a crashing penalty so violations are hard to miss .build() ) StrictMode.setVmPolicy( StrictMode.VmPolicy.Builder() .detectActivityLeaks() .detectLeakedClosableObjects() .detectLeakedRegistrationObjects() .detectLeakedSqlLiteObjects() .penaltyLog() .build() ) }
  • (docs) ThreadPolicy watches one thread (the one you set it on), VmPolicy watches 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.

// A classic leak: a long-lived object holds a short-lived one object NotesCache { var screenCallback: (() -> Unit)? = null // a global (long-lived) variable... } @Composable fun NotesScreen() { val context = LocalContext.current // an Activity NotesCache.screenCallback = { Toast.makeText(context, "Hi", Toast.LENGTH_SHORT).show() } // ...the lambda captures the Activity, and the object lives as long as the app does: // the Activity cannot be garbage-collected after rotation or finish(). } // The fix: do not park UI references in long-lived objects; clear them when the screen is // disposed, e.g. DisposableEffect(Unit) { onDispose { NotesCache.screenCallback = null } }
  • (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.

// The generator (docs: BaselineProfileRule, in the Baseline Profile module) @RunWith(AndroidJUnit4::class) class BaselineProfileGenerator { @get:Rule val rule = BaselineProfileRule() @Test fun generate() = rule.collect(packageName = "com.example.notes") { pressHome() startActivityAndWait() // Walk the journeys users take most: scroll the list, open a note } }
// Tell the benchmark (and the system) when the screen is really ready (docs: ReportDrawnWhen) @Composable fun NotesScreen(state: NotesUiState) { ReportDrawnWhen { !state.isLoading } // ... }
// A Macrobenchmark module (docs: use the Baseline Profile / Macrobenchmark module templates) @RunWith(AndroidJUnit4::class) class StartupBenchmark { @get:Rule val benchmarkRule = MacrobenchmarkRule() @Test fun startupNoCompilation() = startup(CompilationMode.None()) @Test fun startupBaselineProfile() = startup(CompilationMode.Partial()) // docs' comparison private fun startup(mode: CompilationMode) = benchmarkRule.measureRepeated( packageName = "com.example.notes", metrics = listOf(StartupTimingMetric()), iterations = 10, startupMode = StartupMode.COLD, compilationMode = mode ) { pressHome() startActivityAndWait() } }
  • (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 StartupTimingMetric and CompilationMode. 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) ReportDrawnWhen tells 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 aosp image; 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

  1. Turn on R8 and measure again (Chapter 5; general knowledge about how big the win usually is: check on your app).
  2. Run StrictMode in debug and fix what it reports.
  3. Add a baseline profile and compare start-up.
  4. Only then look at individual composables, and only the ones a trace points at.
Compared with the Classic UI course
Android Development: Production & Publishing 6 teaches performance and optimisation: profiling, memory, ANRs and baseline profiles. The tools are the same; this edition leans on Macrobenchmark and the Compose drawn-state APIs, and ties R8 (Chapter 5) and the Compose habits (Chapter 1) into one measuring routine.

Try It Yourself

Exercise 1

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 solution
Exercise 2

Create 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 solution
Exercise 3

Add 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 solution
Not Yet Verified
Checked in the docs (three searches, summaries only): the baseline-profile recommendation, templates and generation; the profile scope beyond startup; ReportDrawn 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).
Coming up
Chapter 7 is Publishing to Google Play: signing, app bundles, the Play Console, the store listing and release tracks, all described from the docs, since none of it can be done for you here.