10-performance.md
.codex/skills/compose-kotlin-agent-skills/references/10-performance.md
1# Performance — Recomposition, Stability, LazyColumn, Baseline Profiles23## Contents45- Recomposition debugging6- Stability annotations7- derivedStateOf8- LazyColumn optimization9- Image loading — Coil 310- Baseline profiles1112## Recomposition Debugging1314### Layout Inspector15161. Run app in debug mode172. Android Studio → Layout Inspector → Select process183. Enable "Show Recomposition Counts" in toolbar194. Recomposition count shows how many times each composable recomposed205. High numbers on static composables = problem2122### Compose Compiler Metrics2324```bash25# Add to build.gradle.kts26kotlinOptions {27 freeCompilerArgs += listOf(28 "-P", "plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=${project.buildDir}/compose_metrics",29 "-P", "plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=${project.buildDir}/compose_reports"30 )31}32```3334Generates:35- `*-composables.txt` — stability of each composable's params36- `*-classes.txt` — stability of each class37- `*-module.json` — summary stats3839Look for `UNSTABLE` params. Each unstable param prevents skipping.4041## Stability Annotations4243### @Immutable — Value Never Changes4445```kotlin46@Immutable47data class AccountsUiState(48 val accounts: List<AuthAccount> = emptyList(),49 val searchQuery: String = "",50 val isLoading: Boolean = false51)52```5354Promise to compiler: once constructed, no property changes. Enables skipping when same instance passed.5556### @Stable — Changes Are Observable5758```kotlin59@Stable60class ThemeManager {61 var themeMode by mutableStateOf(ThemeMode.SYSTEM)62 private set6364 fun setTheme(mode: ThemeMode) { themeMode = mode }65}66```6768Promise to compiler: if value changes, Compose snapshot system will know. Use for classes with `mutableStateOf` properties.6970### When NOT to Annotate7172```kotlin73// Already stable — primitives, String, enum74data class SimpleState(val count: Int, val name: String) // auto-stable7576// Don't lie — if class has var properties without mutableStateOf, @Stable is a lie77@Stable // WRONG — regular var, Compose can't observe changes78class BadManager {79 var count = 0 // not mutableStateOf, changes invisible to Compose80}81```8283## derivedStateOf8485Memoize computed state — recalculates only when dependencies change.8687```kotlin88@Composable89fun AccountsList(accounts: List<AuthAccount>, searchQuery: String) {90 // WRONG — recomputes on every recomposition91 val filtered = accounts.filter { it.serviceName.contains(searchQuery) }9293 // RIGHT — only recomputes when accounts or searchQuery changes94 val filtered by remember(accounts, searchQuery) {95 derivedStateOf {96 accounts.filter { it.serviceName.contains(searchQuery, ignoreCase = true) }97 }98 }99100 LazyColumn {101 items(filtered, key = { it.id }) { AccountCard(it) }102 }103}104```105106### When derivedStateOf Matters107108```kotlin109// Show "scroll to top" FAB only when scrolled past threshold110val listState = rememberLazyListState()111112// WRONG — rechecks on every scroll pixel, triggers recomposition113val showFab = listState.firstVisibleItemIndex > 0114115// RIGHT — only triggers recomposition when crossing threshold116val showFab by remember {117 derivedStateOf { listState.firstVisibleItemIndex > 0 }118}119```120121**Rule:** use `derivedStateOf` when:1221. State reads change frequently (scroll position, text input)1232. Derived value changes less frequently than input (boolean threshold from int)1243. Computation is non-trivial (filtering, sorting)125126**Skip when:** input changes at same rate as output (simple property access).127128## LazyColumn Optimization129130### Keys — Always Provide131132```kotlin133// WRONG — positional identity, breaks on reorder/delete134LazyColumn {135 items(accounts) { AccountCard(it) }136}137138// RIGHT — stable key, correct identity across changes139LazyColumn {140 items(accounts, key = { it.id }) { AccountCard(it) }141}142```143144### contentType — Enable Item Reuse145146```kotlin147LazyColumn {148 item(contentType = "header") {149 SectionHeader("Active Accounts")150 }151 items(152 items = activeAccounts,153 key = { it.id },154 contentType = { "account_card" } // Compose reuses composition for same type155 ) { account ->156 AccountCard(account)157 }158 item(contentType = "header") {159 SectionHeader("Archived")160 }161 items(162 items = archivedAccounts,163 key = { it.id },164 contentType = { "account_card" }165 ) { account ->166 AccountCard(account)167 }168}169```170171### Avoid Allocations in Item Scope172173```kotlin174// WRONG — new lambda every item, every recomposition175items(accounts, key = { it.id }) { account ->176 AccountCard(177 account = account,178 onClick = { viewModel.selectAccount(account.id) } // new lambda each time179 )180}181182// RIGHT — remember lambda with stable key183items(accounts, key = { it.id }) { account ->184 val onClick = remember(account.id) {185 { viewModel.selectAccount(account.id) }186 }187 AccountCard(account = account, onClick = onClick)188}189```190191### Avoid Nesting Scrollable Containers192193```kotlin194// WRONG — crashes or infinite size195Column(modifier = Modifier.verticalScroll(rememberScrollState())) {196 LazyColumn { /* CRASH */ }197}198199// RIGHT — single LazyColumn with mixed content200LazyColumn {201 item { Header() }202 item { SearchBar() }203 items(accounts, key = { it.id }) { AccountCard(it) }204 item { Footer() }205}206```207208## Image Loading — Coil 3209210```kotlin211// Setup — in Application or DI212val imageLoader = ImageLoader.Builder(context)213 .crossfade(true)214 .memoryCachePolicy(CachePolicy.ENABLED)215 .diskCachePolicy(CachePolicy.ENABLED)216 .build()217218// Usage in Composable219AsyncImage(220 model = ImageRequest.Builder(LocalContext.current)221 .data(account.iconUrl)222 .crossfade(300)223 .placeholder(R.drawable.ic_placeholder)224 .error(R.drawable.ic_error)225 .build(),226 contentDescription = "${account.serviceName} icon",227 modifier = Modifier228 .size(48.dp)229 .clip(CircleShape),230 contentScale = ContentScale.Crop231)232```233234### Coil in LazyColumn — Avoid Refetching235236```kotlin237items(accounts, key = { it.id }) { account ->238 // Coil caches by URL — same URL won't refetch239 // But provide key to LazyColumn so item identity is stable240 AsyncImage(241 model = account.iconUrl,242 contentDescription = null,243 modifier = Modifier.size(40.dp).clip(CircleShape)244 )245}246```247248```toml249[dependencies]250coil-compose = { module = "io.coil-kt.coil3:coil-compose", version.ref = "coil" }251coil-network-okhttp = { module = "io.coil-kt.coil3:coil-network-okhttp", version.ref = "coil" }252```253254## Baseline Profiles255256Precompile critical user paths ahead of time for faster startup and smoother scrolling.257258### Generate259260```kotlin261// Create benchmark module — app/src/androidTest/262@RunWith(AndroidJUnit4::class)263class BaselineProfileGenerator {264 @get:Rule265 val rule = BaselineProfileRule()266267 @Test268 fun generateProfile() {269 rule.collect(270 packageName = "com.example.app",271 stableIterations = 3,272 maxIterations = 10273 ) {274 // Critical user journey275 startActivityAndWait()276 device.findObject(By.text("Accounts")).click()277 device.waitForIdle()278 // Scroll the list279 device.findObject(By.res("account_list")).also { list ->280 list.fling(Direction.DOWN)281 list.fling(Direction.UP)282 }283 }284 }285}286```287288### Apply289290```kotlin291// build.gradle.kts (app)292dependencies {293 implementation("androidx.profileinstaller:profileinstaller:1.4.1")294 baselineProfile(project(":benchmark"))295}296297baselineProfile {298 automaticGenerationDuringBuild = true299}300```301302### Verify303304```bash305# Check if profile is included in APK306unzip -l app-release.apk | grep "baseline"307# Should show: assets/dexopt/baseline.prof308```309310**Impact:** 20-40% faster startup, smoother first scroll in LazyColumn. Free performance — no code changes needed.311312## Anti-Patterns313314- **Not providing keys in LazyColumn** → item identity by position breaks on reorder/delete315- **`@Stable` on class with plain `var`** → lie to compiler. Use `mutableStateOf` for observable state316- **`derivedStateOf` for everything** → adds overhead for simple pass-through. Only when input changes faster than output317- **`remember {}` without keys** → stale value when params change. Add dependencies as keys318- **Loading full-resolution images in list** → OOM. Use Coil with size constraints, or thumbnail URLs319- **Skipping baseline profiles** → free 20-40% startup improvement. Generate and ship320