协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
jetpack-compose-performance指导Compose状态、布局、列表、动画和绘制性能审查;需真实工程及测量证据,不保证性能提升。
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: jetpack-compose-performance description: Diagnose and optimize Android Jetpack Compose UI code. Use this skill when analyzing performance bottlenecks of existing code to minimize recomposition overhead and prevent dropped frames and UI lag. license: Complete terms in LICENSE.txt metadata: author: Google LLC last-updated: '2026-10-13' keywords:
Before micro-optimizing composables, ensure standard production flags are in place:
@Composable function, modifier chain, and lazy-layout data model against all checklist rules rather than stopping after the first issue found.references/*.md file for the approved fix pattern and full scope guards before reporting a finding or editing code. Never rely on the summary bullets alone to write fixes.MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/state-and-stability.md.
Modifier.offset or Modifier.graphicsLayer) so reads occur in Layout or Draw phase rather than Composition.Read -> Write, or Composition Read -> Layout or Draw Write). Prevent backwards writes across phases to avoid first-frame popping, jank, and infinite recomposition loops (Backwards Write). Do not flag a state assignment at the start of a composable (Write -> Read or Composition Write -> Draw Read) as a backwards write---a backwards write strictly requires a read of that state to precede the write.Write -> Read) : Do not wrap synchronous values in remember { mutableStateOf(...) } only to overwrite them immediately at the top of composition before reading them (for example, var path by remember { mutableStateOf(Path()) }; path = viewModel.getPath()). While not a backwards write, this adds unnecessary slot table and MutableState snapshot overhead (and risks becoming a backwards write if a read is later added preceding the assignment); use a plain local val or read the value directly inside the target phase (such as Modifier.drawWithCache).remember Keys & Slot Overhead : Always pass all input variables and composable parameters referenced inside remember as calculation keys. Remember that remember stores keys + 1 objects in the slot table and checks key equality on every recomposition; only remember when allocations are heavy or identity must be preserved. Do not pass snapshot state values/properties (e.g. state.value) as keys when wrapping derivedStateOf (passing the State instance itself is fine if the instance reference can change).computedStateOf vs derivedStateOf (Compose 1.13+) : On Compose 1.13+, use computedStateOf for simple condition checks and filtered state from fast-changing inputs (such as scrollState.value > 0), which provides significantly faster invalidation than derivedStateOf (on Compose < 1.13, use remember { derivedStateOf { ... } }). Reserve derivedStateOf for heavy calculations that benefit from multi-read caching, or trivial calculations read frequently enough per composition (roughly 10 / numberOfStatesReadPerCalculation times without invalidating between reads) to make up for the invalidation cost.produceState + snapshotFlow blocks observing Compose states (such as scroll positions or collection sizes); replace them with synchronous remember { derivedStateOf { ... } } (or computedStateOf on Compose 1.13+).get()) over derivedStateOf or computedStateOf for simple boolean expressions and property lookups.mutableListOf() and mutableStateOf(list, neverEqualPolicy()) with load-bearing assignments instead of mutableStateListOf().SnapshotStateList.toList() for repeated queries or iterations to avoid per-element read observation overhead.State property reads into a local variable at the top of the block.State inside custom property setters; use a raw backing field when triggering change side-effects and batch multi-property updates.@Immutable, @Stable, or ImmutableList as default solutions. Skipping a composable is not free: each parameter is stored in the slot table as if remembered, and all inputs must be compared on recomposition. Strong Skipping Mode already skips composables with unstable parameters (including standard kotlin.collections.List) when instance equality (===) matches. Annotating models or using ImmutableList forces structural equality (.equals()), which can be significantly more expensive than recomposition itself for large collections or complex classes.@Stable, @Immutable, or ImmutableList to Collection
Models : When writing or optimizing code, never add @Immutable or @Stable to models containing collections (List, Set, Map), and never recommend replacing kotlin.collections.List<T> with ImmutableList<T> (or adding ImmutableList to stability_config.txt). Calling O(N) .equals() on collections on every recomposition pass is more expensive than O(1) instance equality (===) under Strong Skipping Mode.@Stable / @Immutable Annotations
(Large Lazy Datasets Only) :
@Stable or @Immutable annotations from data models when both conditions are met: (1) the model is used within a lazy layout (LazyColumn, LazyRow, LazyGrid, Pager, ScalingLazyColumn) as the input feed or item model, and (2) it contains a large dataset or deep nested
collection hierarchy (e.g., feed streams, large lists of tags/items, or multi-level nested lists like Post with List<Paragraph> and List<Markup>), where recursive O(N) .equals() checks degrade scrolling and recomposition performance.@Stable, @Immutable, or ImmutableList usages in a codebase---such as non-lazy UI models, standalone components, or models with small/bounded collections (e.g., a card with a few badges, thumbnails, or metadata rows) where dataset size is small or unknown---leave the existing
annotations untouched and do not flag them . Never blindly grep and flag all @Stable/@Immutable classes across a codebase without verifying they feed a lazy layout with a large dataset.@Stable / @Immutable Under Strong Skipping Mode : Flat data classes with val primitive/String properties in Compose modules are already inferred as stable by the compiler and use .equals() automatically---do not add redundant @Immutable annotations to them. Only add @Stable or @Immutable when the compiler cannot infer stability (e.g. classes from non-Compose modules or interfaces) and a data source (such as Room or MVI reducers) allocates new object instances for unchanged items on every emission, provided the class is small, flat, has no collections (List, Set, Map), and its .equals() check is trivial O(1).MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/layouts.md.
onGloballyPositioned; use Modifier.onVisibilityChanged for viewport tracking, Modifier.onPlaced or Modifier.onLayoutRectChanged for local bounds, and query requireLayoutCoordinates() on demand inside Modifier.Node event handlers.Layout : When attaching floating labels or tooltips to a component, use a custom Layout measuring and placing both children relative to each other. Never track onGloballyPositioned coordinates in MutableState to position floating content with offset, which causes a 1-frame lag and schedules a second composition pass.Modifier.offset { IntOffset(...) }) to skip Composition straight to Layout.Boxes and decorative Canvas nodes; attach modifiers directly or use Modifier.drawBehind.BoxWithConstraints / SubcomposeLayout inside hot paths and lazy items; prefer standard modifiers, Modifier.layout, or LayoutModifierNode.MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/lazy-layouts.md.
key and contentType apply strictly to Lazy containers (LazyColumn, LazyRow, LazyGrid). Never flag standard non-lazy containers (Column, Row, Box) iterating over collections.contentType and Primitive key : Always specify both primitive keys (Int, Long, String) and contentTypes for all items in lazy layouts (LazyColumn, LazyRow, LazyGrid). When using items or itemsIndexed, never omit contentType: contentType = { _, item -> item.type }. Omitting contentType prevents Compose from reusing composition slots during scrolling.list.indexOf(item) with itemsIndexed to eliminate O(N²) lookups during layout passes.mutableStateListOf to an immutable Set in MutableState (mutableStateOf(emptySet<String>())), mutableStateSetOf(), or Map for O(1) lookups. Pass lambda providers (isSelected: () -> Boolean) to leaf composables to isolate recomposition from parent items scopes.CompositionLocals (LocalContext.current, LocalDensity.current, LocalSharedTransitionScope.current, scopes, etc.) inside individual lazy item composables; resolve them once in the parent container or screen and propagate the resolved values down as parameters.Modifier.sharedBounds or Modifier.sharedElement on lazy items behind visibility indicators (such as Modifier.onVisibilityChanged or viewport visibility checks) so offscreen or pre-fetched items do not instantiate transition scopes..size directly instead of wrapping list counts in derivedStateOf.Row or Column with for or forEach loops for small or bounded collections (e.g. 1 to 10 items) to eliminate lazy virtualization, measuring, and pre-fetching overhead.Flows once in the parent container preceding lazy layouts; never call collectAsStateWithLifecycle() per visible item.LaunchedEffect(Unit) inside lazy items; use Modifier.onVisibilityChanged with dwell thresholds instead.MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/animation.md.
Modifier.graphicsLayer { ... } to bypass Composition and evaluate directly in the Draw phase.Modifier.offset { IntOffset(...) } and animate constraints using Modifier.layout { ... } or Modifier.animateBounds to bypass recomposition during size transitions.Modifier.sharedBounds or Modifier.sharedElement only when visible using Modifier.onVisibilityChanged to avoid modifier and observation instantiation costs on discarded pre-fetched items.() -> Float) instead of raw animated values to child composables to keep state reads deferred to Draw or Layout.Animatable in Nodes : Store Animatable as a persistent member property on Modifier.Node and launch in onAttach() using coroutineScope.launch.MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/effects-and-threading.md.
SideEffect, LaunchedEffect, or user event callbacks.LaunchedEffect & Empty DisposableEffect : Never use LaunchedEffect for synchronous operations (e.g. logging views or updating objects). Never use DisposableEffect with an empty onDispose {} block as a workaround. Use SideEffect instead (in Compose 1.12+, SideEffect(keys) { ... } supports keys directly; on Compose < 1.12, SideEffect takes no arguments, so check the project's Compose version and track key changes with a remembered holder inside SideEffect { ... }).remember.LaunchedEffects : Combine multiple LaunchedEffect(Unit) calls into a single LaunchedEffect with nested launch { ... } blocks to reduce effect node allocations and coroutine launcher overhead.DisposableEffect > SideEffect > Layout and Draw > LaunchedEffect after frame). Note that canceling a LaunchedEffect incurs coroutine cancellation and teardown overhead; avoid cycling LaunchedEffect keys frequently during animations or scrolling.withContext(Dispatchers.IO) using produceState.LaunchedEffect or DisposableEffect inside lazy items for impression logging. Lazy items are pre-composed before entering the viewport, causing premature or false impressions. Use Modifier.onVisibilityChanged with dwell thresholds instead.collectAsStateWithLifecycle() for UI Flow collections that actively produce background work on Android, and collectAsState() for lightweight in-memory StateFlows or non-Android scopes.BroadcastReceivers once at the screen level using DisposableEffect, not inside lazy list items.if (callback != null) before launching to prevent allocating empty coroutines and effect nodes.rememberUpdatedState when long-running or looping coroutines in LaunchedEffect reference callbacks or parameters.Handler.postDelayed or TimerTask with LaunchedEffect and delay().MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/graphics-performance.md.
Canvas nodes with Modifier.drawWithCache to cache Path, Paint, and Brush allocations.AsyncImage for loading images from the internet and painterResource for drawables. Image is not optimized for caching and loading images and may cause performance issues.remember the RuntimeShader and ShaderBrush in composition, update size uniforms in drawWithCache, and per-frame uniforms in onDrawBehind.Path.rewind() over reset() in hot draw loops to retain allocated buffers without reallocation.Pair, Triple) and generic sets (HashSet<Long>); use androidx.collection.MutableLongSet and androidx.compose.ui.util.packInts.Modifier.Node (Custom modifiers guide)Modifier.Node Migration : Migrate legacy Modifier.composed to
ModifierNodeElement + Modifier.Node (or DelegatingNode when delegating
to sub-nodes such as SuspendingPointerInputModifierNode) with capability
interfaces (DrawModifierNode, LayoutModifierNode,
SemanticsModifierNode, CompositionLocalConsumerModifierNode using
currentValueOf(...)) to eliminate per-node subcomposition overhead and
enable node reuse (see Create custom modifiers with Modifier.Node):
// Modifier factory
fun Modifier.circle(color: Color) = this then CircleElement(color)
// ModifierNodeElement
private data class CircleElement(
val color: Color
) : ModifierNodeElement<CircleNode>() {
override fun create() = CircleNode(color)
override fun update(node: CircleNode) {
node.color = color
}
}
// Modifier.Node
private class CircleNode(
var color: Color
) : DrawModifierNode, Modifier.Node() {
override fun ContentDrawScope.draw() {
drawCircle(color)
}
}
On-Demand Coordinates : Query requireLayoutCoordinates() on demand
inside pointer or draw handlers in Modifier.Node rather than implementing
GlobalPositionAwareModifierNode.onGloballyPositioned.
IMPORTANT : For more examples on how to migrate common modifiers to Modifier.Node, you must read Create custom modifiers with Modifier.Node.