Performance and UI Rendering
Scope: cold/warm startup, main-thread blocking and ANRs, frame timing/jank, Compose recomposition and layout cost, list-scrolling performance, memory/allocation/image-loading issues, and which profiling tool to reach for.
Hard rule: no optimization is "done" without a measurement. State what you measured, how (tool + metric), on what (device/emulator, build type — profile release-like builds, not debug), and under what repeated conditions. "This should be faster" is a hypothesis, not a result.
1. Startup (cold / warm)
- Cold start = process not in memory; warm start = process alive, activity recreated; hot start = activity already in memory, just brought to foreground. Each has different bottlenecks — don't treat them as one number.
- Primary offenders: heavy work in
Application.onCreate()(DI graph construction, eager singleton init, disk I/O, network calls), unnecessaryContentProviders initializing at app start, oversized/synchronousonCreate()in the launchActivity, and large numbers of eagerly-inflated views. - Measure with Macrobenchmark's
StartupTimingMetric, oradb shell am start -Wfor a quick manual check (reportsThisTime/TotalTime/WaitTime). Macrobenchmark is the repeatable, CI-friendly option;am start -Wis fine for a quick local sanity check but is noisier. - Baseline Profiles pre-compile hot-path classes/methods ahead of time (via ART) to cut JIT/interpretation cost on first run — generate and measure the delta with Macrobenchmark rather than assuming a Baseline Profile helped.
reportFullyDrawn()lets you mark when the screen is actually usable (not just first-frame-drawn), which is whatTotalTimeand Play Console's startup vitals key off — call it once your critical content (not just a spinner) is on screen.
2. Main-thread blocking and ANRs
- An ANR fires when the main thread doesn't respond to input within ~5s, or a
BroadcastReceiverdoesn't finish within its window — but felt jank happens at far smaller main-thread stalls (a single dropped 16.6ms/8.3ms frame is already user-visible at 60/120Hz). - Look for: synchronous disk/database/network I/O on the main thread (Room queries not run via
suspend/Flow,SharedPreferences.commit()instead ofapply(), direct file I/O), unbounded work insideonDraw/onMeasure/onLayoutor a composable's body, and large JSON/object (de)serialization on the main thread. StrictMode(StrictMode.setThreadPolicy) catches disk/network-on-main-thread violations in debug builds — recommend enabling it in debug builds if it isn't already, rather than inventing bespoke static detection.- For reproducing/diagnosing an ANR after the fact, Play Console's ANR reports plus on-device
/data/anr/traces.txt-equivalent captures (oradb shell am dumpsysat the time) show which thread held what — treat a hypothesis about "which call caused this ANR" as unconfirmed until a trace backs it up.
3. Frame timing, jank, dropped frames
- Target frame budget is ~16.6ms at 60Hz (or ~8.3ms at 120Hz) end-to-end per frame; a frame that misses its vsync deadline is "janky" and gets displayed late or dropped.
- JankStats (Jetpack library) instruments real frame timing in-app and classifies frames (including attributing jank to specific UI states via
JankStats.Builder's state tracking) — the right first tool for "is this screen janky in production/CI, and which frames." - Perfetto traces give the systrace-level view (what ran on which thread, when) needed to find why a frame was slow, not just that it was. Use custom trace sections (
Trace.beginSection/androidx.tracing) around suspect code to make them show up clearly. - Don't chase jank by guesswork — capture a trace or JankStats report first, identify the actual slow frame(s) and what was running during them, then fix, then re-measure the same way.
4. Jetpack Compose recomposition and layout cost
- Unstable parameters (a lambda capturing changing state, a mutable
List/non-@Immutable/non-@Stabledata class) cause composables to recompose more than necessary. Use the Compose Compiler metrics/reports to find what's unstable before manually hunting through code. remember/derivedStateOfshould wrap genuinely expensive computations or state reads that shouldn't trigger recomposition of everything depending on them — overusingrememberfor trivial values adds complexity without a measured benefit; profile before adding it.- Layout: deeply nested
Column/Row/Boxhierarchies and customLayouts that do expensive measurement work on every pass show up as layout-phase cost, distinct from recomposition cost — the Layout Inspector and Compose's own tracing sections in Perfetto distinguish composition vs. layout vs. draw phases. @Stable/@Immutableannotations are a contract, not a suggestion — applying them to a class that doesn't actually satisfy the contract (e.g. a "stable" class whose public properties can change without recomposition being notified) causes incorrect skipping and stale UI, which is worse than the recomposition it was meant to prevent.- Since Kotlin 2.0.20, the Compose compiler's strong skipping mode is on by default: composables are skippable even when one of their parameters is otherwise-unstable, as long as that parameter is compared by reference equality across recompositions (lambdas included) — this closes a large class of "why didn't this skip" surprises from before, but it only reaches actual
@Composablescopes, not plain non-composable lambdas/functions called from one. A plain mutableList/Mapparameter is still unstable either way — preferkotlinx.collections.immutable'sImmutableList/ImmutableMap/etc. (or a@Immutable-annotated wrapper that's actually immutable) over hand-annotating a mutable collection type, which is a contract violation per the point above.
5. RecyclerView and LazyColumn/LazyRow
- RecyclerView: check
DiffUtilis used for list updates (notnotifyDataSetChanged()on every change), view holders don't do heavy work inonBindViewHolder(defer to background work + bind the result), andsetHasFixedSize(true)is set when applicable. Nested RecyclerViews and deeply nested view hierarchies in item layouts are common jank sources on scroll. - LazyColumn/LazyRow: always supply stable
keys per item (from a stable ID, not the index) so Compose can track item identity across scroll/reordering/insertion without over-recomposing or losing scroll position; usecontentTypewhen the list mixes item shapes so the item-composable pool can be reused correctly. Inside an item composable, preferModifier.fillParentMaxWidth()/fillParentMaxSize()over plainfillMaxWidth()/fillMaxSize()when you actually want the item sized relative to the lazy list's viewport — an item's own measurement scope doesn't carry the parent's incoming constraints the way a normalColumn/Boxchild would, so plainfillMaxWidth()inside a lazy item can silently size against the wrong constraint. - Don't call an O(n) lookup like
list.indexOf(item)from inside anitems {}item factory to compute per-item data (e.g. "is this the last item") — it runs on every recomposition of every visible item, turning an O(n) list into effectively O(n²) scroll behavior. Precompute the needed index/lookup once (aMapkeyed by ID, or the index captured at theitemsIndexedcall site) outside the per-item scope instead. reportFullyDrawn()(§1) marks a whole screen usable; for a list-first screen specifically, Compose'sReportDrawnWhen/ReportDrawncomposables let that condition be "the list's first page of real content has actually laid out" (e.g. gated onlazyListState.layoutInfo.totalItemsCount > 0) rather than firing unconditionally on first frame, which gives a more accurate startup-timing signal for list-first screens.- Both: expensive image decode/transform work must happen off the main thread with results cached (see §6) — scrolling perf is often an image-loading problem wearing a RecyclerView/LazyColumn costume.
6. Memory, allocations, and image loading
- Repeated allocations inside hot paths (a composable body,
onBindViewHolder, a scroll listener) create GC pressure that shows up as jank even without an outright leak — look for object/lambda/collection allocation inside loops or per-frame callbacks. - Memory leaks in Android are usually a long-lived reference (a singleton, a static field, an unclosed listener/callback) holding onto a short-lived context (an
Activity, aFragment's view). Use LeakCanary for automated leak detection in debug builds rather than manually hunting reference chains first. - Image loading: bitmaps should be loaded at the target display size (not full resolution then downscaled), cached (memory + disk) via a maintained library (Coil, Glide) rather than hand-rolled caching, and decoded off the main thread. Loading full-resolution images into small thumbnails is one of the most common avoidable memory/GC sources in Android apps.
- The Android Studio Memory Profiler (heap dumps, allocation tracking) is the tool for "where did this memory go" questions; don't speculate about allocation sources without one.
7. Picking the right tool
| Question | Tool |
|---|---|
| How long does cold/warm start actually take, repeatably, in CI? | Macrobenchmark |
| Is this specific function/hot-path fast enough, in isolation? | Microbenchmark |
| Can I shave first-run JIT/interpretation cost? | Baseline Profiles |
| Is this screen janky in the field or in an automated test, and on which frames? | JankStats |
| Why, exactly, was this frame/call slow — what ran, on which thread, when? | Perfetto / systrace |
| Why is memory growing / what's leaking? | Android Studio Memory Profiler, LeakCanary |
| Which composables recompose too often, and why? | Compose Compiler metrics/reports, Layout Inspector recomposition counts |
Sources
- Android Vitals / app performance guidance — developer.android.com.
- Macrobenchmark, Microbenchmark, Baseline Profiles — developer.android.com.
- JankStats and Perfetto command-line tracing — developer.android.com.
- Compose performance and stability — developer.android.com.
- LeakCanary — square.github.io.
- Lazy layout item scope (
LazyItemScope) — developer.android.com (for the §5fillParentMaxWidth/fillParentMaxSizefact). - Compose strong skipping mode and
kotlinx.collections.immutable— developer.android.com / Kotlin (for the §4 strong-skipping and immutable-collection facts). - App startup time /
reportFullyDrawn()and theandroidx.activity.composeReportDrawn/ReportDrawnWhenAPIs — developer.android.com (for the §5 list-startup reporting fact). - Tool-selection framing was cross-checked against the scope of
android/skills' Profilers/Performance domains andliuyi0808/android-review'sperformanceskill. The §5 lazy-layout sizing idiom was cross-checked againstRanaNadeemAslam/android-ai-skills'sperformance.mdand verified against the officialLazyItemScopeAPI docs above (structure/idioms referenced, no text copied — seedocs/SOURCE_MAPPING.md). - The §4 strong-skipping-mode and immutable-collections facts were cross-checked against
rcosteira79/android-skills'compose/references/performance.md, and the §5indexOf()/O(n²) andReportDrawnWhenfacts against itscompose/references/lists-scrolling.md, each verified against the official docs above before being written in this project's own words (structure/idioms referenced, no text copied — seedocs/SOURCE_MAPPING.md).