Measurement-first performance work for Kotlin. Pair with kotlin-patterns for idiomatic code and android-testing for the test harness that hosts benchmarks.
If the target is a pure JVM library or CLI, most guidance transfers — skip the Android sections.
Measure on-device against release builds. Debug APKs run interpreted or with limited AOT; measurements are worthless. Macrobenchmark demands release (or a benchmark buildType with signingConfig + debuggable = false + profileable).
Change one variable at a time. Log the baseline (before) and delta (after) with the same device, thermal state, and driver.
Cold vs warm vs hot are three different problems — pick the StartupMode explicitly.
Fix algorithm and data-structure issues first, then allocations, then micro-optimizations.
Do not benchmark on emulators for latency claims. Use a physical device profile with locked CPU governor (adb shell cmd power set-fixed-performance-mode-enabled true when supported, or Gradle-managed devices with enablePerformanceMode = true).
Define the symptom precisely. Cold start / TTID / TTFD, scroll frame time p99, memory retained after N cycles, or throughput ops/sec. Choose one first.
Capture a signed baseline on the target device. Record mean/p50/p90/p99, allocation, and one Perfetto trace.
Analyze. In Perfetto or Android Studio: find hot slices (JIT compilation, GC, layout inflation, androidx.compose.runtime.snapshots). In Compose reports, find non-restartable/non-skippable functions.
Apply one change. Enable R8 full mode, add a Baseline Profile, refactor a specific @Composable, switch a Dispatchers.Default to a bounded pool — one at a time.
Verify. Re-run the same harness on the same device profile. Compare against baseline; reject changes that regress p99 or introduce non-deterministic variance.
ANRs are main-thread availability failures, not crashes. Trace-driven attribution:
Prove the executing thread and prove the call blocks before attributing a candidate ANR cause — stack lines alone mislead when dispatchers or proxies are involved.
Attribute in the trace as APP_DEFECT (fix the app), APP_RESOURCE_OVERLOAD (fix resource use), or EXTERNAL_BOTTLENECK (binder/system contention — do not "fix" with app changes).
Sync Barrier Leak: posting to a View from a non-main thread while it is attached can leak the main Looper's sync barrier — every subsequent frame/measure pass queues behind it and the app ANRs with no obvious blocker on the main thread. Audit off-main mutations of attached Views; check for an unremoved SyncBarrier in the trace's Looper state.
Common main-thread blockers to look for in the dump: binder calls held across lock acquisition, SharedPreferences first-load, layout inflation of deep hierarchies, synchronous I/O in BroadcastReceiver.
#Android release-build knobs (measure each in isolation)
R8 full mode: default on AGP 9 (no android.enableR8.fullMode=true needed; the false opt-out is gone in AGP 10). On AGP 8.x: enable via gradle.propertiesand use proguard-android-optimize.txt (proguard-android.txt is rejected by AGP 9). Typical: 5–15% smaller APK + faster startup. Full mode enables horizontal class merging, vertical class merging, and interface-method rewriting — will break some reflection-heavy libraries. Verify at runtime, not just compile. AGP 9.3+ adds the optimization {} DSL and the analyzeReleaseR8Config Configuration Analyzer task (report in build/reports/r8/) to audit keep rules.
shrinkResources = true (paired with minifyEnabled = true) — required to strip unused resources. AGP 8.7+ supports optimized resource shrinking for ~30% resource file reduction.
Baseline Profile: androidx.baselineprofile Gradle plugin generates baseline-prof.txt from a Macrobenchmark journey run on a nonMinified build. R8 rewrites the rules to match the minified release (introduced in Baseline Profile 8.2+; ~30% method coverage improvement).
Startup Profile: same generator, includeInStartupProfile = true. Rearranges DEX layout so critical startup classes land in classes.dex — measurable startup win on top of Baseline Profile.
PGO for the app process itself: profiles collected via adb shell pm dump-profiles <pkg> can be committed as Cloud Profile input — reserved for late-cycle tuning.
Enable together only after each has been measured separately.
Review the *-classes.txt output: every class not marked stable breaks skipping. Fix by marking stable in the config file, using @Immutable/@Stable, or wrapping in a stable holder.
Strong skipping mode (Compose Compiler 1.5.4+, default in newer AGP): treats unstable parameters as @Stable when they're equal by structural equality. Reduces recomposition for common patterns (e.g. lambdas with unstable captures) but must be verified with a trace — some hot Composables still need explicit fixes.
Recomposition tracing: Macrobenchmark 1.4+ supports perfettoSdkTracing = true — recompositions appear in the Perfetto trace as named slices. Look for slice counts that exceed expected recomposition rounds per user interaction.
Modifier chain hot paths: prefer Modifier.Node API (Compose 1.7+) for custom modifiers over Modifier.composed { }, which allocates on every recomposition.
Dispatcher choice at the leaf, not the caller.withContext(Dispatchers.IO) around genuine blocking I/O; Default for CPU-bound. IO has an unbounded thread pool (~64 threads by default) — starving Default with I/O work is a common jank source.
limitedParallelism(n) on Dispatchers.IO for controlled parallelism (Dispatchers.IO.limitedParallelism(4)). Prevents thread explosion under load spikes.
Backpressure operators on Flow:
buffer(n) — decouples producer and consumer with a bounded queue. Use when both are CPU-bound but at different rates.
conflate() — drops intermediate values, keeps only the latest. UI state pipelines.
collectLatest { } — cancels the previous block on new emission. Search-as-you-type.
debounce(ms) / sample(ms) — throttle by time. User input flows.
Every launch { } allocates a StandaloneCoroutine; async { } allocates a DeferredCoroutine. In a hot loop, prefer map { } on a Flow over launching per-item.
Avoid withContext(Dispatchers.Main) in the middle of a leaf function — the context switch cost dominates for microsecond-scale work.
LeakCanary is now natively integrated into Android Studio Otter (2025.2+) Profiler as a "LeakCanary task"; still install the library on debug builds for continuous detection. In CI/dev, keep LeakCanary.config = LeakCanary.config.copy(retainedVisibleThreshold = 1) for aggressive detection.
Typical Android leak sources:
Context/Activity/View held in singletons, static fields, or object bodies.
Fragment view listeners bound to Fragment.lifecycleOwner instead of viewLifecycleOwner.
Handler(Looper.getMainLooper()) with postDelayed referencing a View.
GlobalScope.launch { } capturing an Activity.
Heap dumps: Android Studio → Memory Profiler → Capture Heap Dump. Filter by class, sort by "Retained Size". Compare two dumps N minutes apart to find growth.
adb shell dumpsys meminfo <pkg> gives a quick view of PSS, private clean/dirty, DEX/code. Compare across builds.
Measuring on debug builds → interpreter overhead dominates; conclusions are wrong.
Enabling R8 full mode without testing → reflection-heavy libraries (Gson, Retrofit, Room without keep rules, older Moshi) break at runtime with NoSuchMethodException. Ship staged rollout.
Baseline Profile generated on a non-representative journey → covers the wrong methods. Use realistic user flows, not synthetic loops.
SharingStarted.Eagerly on repository Flows → keeps upstream alive forever, leaks work and memory. Use WhileSubscribed(5_000).
Dispatchers.IO for CPU-bound work → starves the shared thread pool; use Default or a limitedParallelism slice.
Unstable lambdas captured in a hot @Composable → busts skipping. Hoist state or convert to remember { }-scoped values.
for (i in 0..list.size - 1) in a hot loop with an Iterable → boxes Int; use forEach / for (item in list) for concrete lists.
references/macrobenchmark-and-microbenchmark.md — end-to-end setup, StartupTimingMetric, FrameTimingMetric, TraceSectionMetric, allocation metrics, Gradle-managed devices, running on Firebase Test Lab; load when setting up the harness
references/baseline-and-startup-profiles.md — Baseline Profile Gradle plugin, generation via BaselineProfileRule, Startup Profile includeInStartupProfile, coverage measurement, Cloud Profile pipeline; load when creating or auditing profiles
references/compose-recomposition.md — compiler stability report, strong skipping, Modifier.Node, LazyColumn key stability, derivedStateOf, Perfetto recomposition tracing; load when Compose scroll or animation is the bottleneck
references/coroutines-and-flow-performance.md — dispatcher pool sizing, limitedParallelism, backpressure operator selection, Flow overhead vs Channel vs suspend, cold-hot conversion cost; load when async pipelines are slow or bursty
references/memory-and-leaks.md — LeakCanary integration, heap dump comparison, retained size analysis, Android memory model (PSS/RSS/SwapPss/DEX/code), native memory triage; load when diagnosing OOM, growth, or leak reports
references/perfetto-and-tracing.md — Perfetto config, custom trace sections, Compose SDK tracing, common track cheatsheet, offline trace analysis with the Trace Processor; load when a symptom needs system-level attribution
references/jvm-benchmarking.md — kotlinx-benchmark / JMH setup, dead-code elimination, warmup strategy, Blackhole usage, comparing runs, running on CI; load when the hot path is non-Android or must be isolated from the runtime