Jetpack Compose Performance
Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)
- Skill
- Review and audit
- Software development
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured audit workflow for identifying and resolving performance issues in Jetpack Compose applications. It covers state management, layout measurement, lazy container optimization, animation, threading, and custom drawing. The guidelines emphasize phase deferral, proper use of state derivation, and efficient modifier implementation to prevent unnecessary recomposition and rendering overhead.
What it does
- Provides an audit checklist for identifying performance bottlenecks in Compose UI code.
- Explains how to defer state reads to Layout or Draw phases to minimize recomposition.
- Offers patterns for optimizing lazy layouts using keys, content types, and efficient state queries.
- Details how to migrate legacy modifiers to the Modifier.Node API for improved efficiency.
- Defines rules for managing side effects, lifecycle-aware flow collection, and threading.
- Outlines best practices for graphics caching and custom drawing performance.
When to use it
- When analyzing UI performance issues such as dropped frames or layout lag.
- When refactoring complex composables to reduce recomposition overhead.
- When optimizing data models and state handling for large lazy lists.
- When implementing custom modifiers or complex drawing operations.
Advantages
- Reduces redundant recomposition passes through phase deferral techniques.
- Provides clear guidance on avoiding backwards writes and infinite recomposition loops.
- Standardizes the implementation of custom modifiers using modern Modifier.Node APIs.
- Helps maintain UI stability and rendering performance in complex Android applications.
Usage examples
- “How can I optimize a frequently recomposing composable that reads state?”
- The agent will guide you to wrap state reads in lambdas or use Modifier.graphicsLayer to defer reads to the Layout or Draw phases, bypassing unnecessary composition.
- “How should I handle state in a LazyColumn to avoid performance issues?”
- The agent will advise on using primitive keys and content types, hoisting state queries, and avoiding O(N) lookups to ensure efficient scrolling and item reuse.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/android/jetpack-compose-performance/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip jetpack-compose-performance.zip -d .agents/skills
Documentation by Google LLC
Foundational prerequisites
Before micro-optimizing composables, ensure standard production flags are in place:
Release Build: Never profile or benchmark debuggable builds; ART runtime verification severely degrades performance.
R8 Minification: Keep R8 enabled to optimize bytecode and coroutine dispatch.
Baseline Profiles: Generate baseline profiles for critical user journeys (cold start, key scrolling feeds) so the ART VM pre-compiles and preloads classes ahead of time.
Optimization audit workflow
Exhaustive Scan : Scan the target code against all 7 core categories in the following sections. Evaluate every
@Composablefunction, modifier chain, and lazy-layout data model against all checklist rules rather than stopping after the first issue found.Mandatory Reference Read Before Flagging or Editing : Whenever a file matches a rule in Categories 1--7, you MUST open and read the corresponding
references/*.mdfile 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.
1. State, snapshots, and stability (references/state-and-stability.md)
MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/state-and-stability.md.
Phase Deferral (Lambdas) : Wrap frequently changing state reads in lambdas (such as
Modifier.offsetorModifier.graphicsLayer) so reads occur in Layout or Draw phase rather than Composition.Prohibit Backwards Writes (Verify Read-Before-Write Order) : Never modify state in a later phase or after it has already been read in the same composition pass (
Read -> Write, orComposition 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 -> ReadorComposition Write -> Draw Read) as a backwards write---a backwards write strictly requires a read of that state to precede the write.Avoid Redundant State Wrapping in Composition (
Write -> Read) : Do not wrap synchronous values inremember { 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 andMutableStatesnapshot overhead (and risks becoming a backwards write if a read is later added preceding the assignment); use a plain localvalor read the value directly inside the target phase (such asModifier.drawWithCache).Explicit
rememberKeys & Slot Overhead : Always pass all input variables and composable parameters referenced insiderememberas calculation keys. Remember thatrememberstoreskeys + 1objects in the slot table and checks key equality on every recomposition; onlyrememberwhen allocations are heavy or identity must be preserved. Do not pass snapshot state values/properties (e.g.state.value) as keys when wrappingderivedStateOf(passing theStateinstance itself is fine if the instance reference can change).computedStateOfvsderivedStateOf(Compose 1.13+) : On Compose 1.13+, usecomputedStateOffor simple condition checks and filtered state from fast-changing inputs (such asscrollState.value > 0), which provides significantly faster invalidation thanderivedStateOf(on Compose< 1.13, useremember { derivedStateOf { ... } }). ReservederivedStateOffor heavy calculations that benefit from multi-read caching, or trivial calculations read frequently enough per composition (roughly10 / numberOfStatesReadPerCalculationtimes without invalidating between reads) to make up for the invalidation cost.Synchronous State Derivation : Audit for asynchronous
produceState+snapshotFlowblocks observing Compose states (such as scroll positions or collection sizes); replace them with synchronousremember { derivedStateOf { ... } }(orcomputedStateOfon Compose 1.13+).Trivial Primitives : Prefer plain custom Kotlin getters (
get()) overderivedStateOforcomputedStateOffor simple boolean expressions and property lookups.Collection State Tracking : Back whole-list updates with standard
mutableListOf()andmutableStateOf(list, neverEqualPolicy())with load-bearing assignments instead ofmutableStateListOf().Snapshot Collections : Use
SnapshotStateList.toList()for repeated queries or iterations to avoid per-element read observation overhead.Repeated State Reads : Extract repeated Compose
Stateproperty reads into a local variable at the top of the block.State in Setters : Avoid reading Compose
Stateinside custom property setters; use a raw backing field when triggering change side-effects and batch multi-property updates.Stability & Skipping Trade-Offs (Skipping Isn't Free) : Do not fixate on stability or treat
@Immutable,@Stable, orImmutableListas 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 standardkotlin.collections.List) when instance equality (===) matches. Annotating models or usingImmutableListforces structural equality (.equals()), which can be significantly more expensive than recomposition itself for large collections or complex classes.Never Add
@Stable,@Immutable, orImmutableListto Collection Models : When writing or optimizing code, never add@Immutableor@Stableto models containing collections (List,Set,Map), and never recommend replacingkotlin.collections.List<T>withImmutableList<T>(or addingImmutableListtostability_config.txt). CallingO(N).equals()on collections on every recomposition pass is more expensive thanO(1)instance equality (===) under Strong Skipping Mode.Scope Guard for Removing Existing
@Stable/@ImmutableAnnotations (Large Lazy Datasets Only) :When to Remove : Only recommend removing existing
@Stableor@Immutableannotations 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 likePostwithList<Paragraph>andList<Markup>), where recursiveO(N).equals()checks degrade scrolling and recomposition performance.When to Leave Untouched : For all other existing
@Stable,@Immutable, orImmutableListusages 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/@Immutableclasses across a codebase without verifying they feed a lazy layout with a large dataset.
When to Add
@Stable/@ImmutableUnder Strong Skipping Mode : Flatdata classes withvalprimitive/Stringproperties in Compose modules are already inferred as stable by the compiler and use.equals()automatically---do not add redundant@Immutableannotations to them. Only add@Stableor@Immutablewhen 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 trivialO(1).Make Composables Cheaper Instead of Forcing Skipping: Do not overindex on recomposition counts. Skipping one composable during an active recomposition pass saves little time once composition is scheduled (scheduling and starting the recomposition pass is the bulk of the cost). Focus on making composables cheap to execute, deferring state reads to Layout/Draw, and verifying with benchmarks rather than assuming skipping improves performance.
2. Layouts and measurement optimization (references/layouts.md)
MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/layouts.md.
Coordinates & Placement : Avoid
onGloballyPositioned; useModifier.onVisibilityChangedfor viewport tracking,Modifier.onPlacedorModifier.onLayoutRectChangedfor local bounds, and queryrequireLayoutCoordinates()on demand insideModifier.Nodeevent handlers.Anchor Floating Content via Custom
Layout: When attaching floating labels or tooltips to a component, use a customLayoutmeasuring and placing both children relative to each other. Never trackonGloballyPositionedcoordinates inMutableStateto position floating content withoffset, which causes a 1-frame lag and schedules a second composition pass.Phase Deferral for Offsets : Wrap dynamic offsets in lambdas (
Modifier.offset { IntOffset(...) }) to skip Composition straight to Layout.Tree Depth & Decorative Wrappers : Avoid redundant wrapper
Boxes and decorativeCanvasnodes; attach modifiers directly or useModifier.drawBehind.Subcomposition Overhead : Avoid
BoxWithConstraints/SubcomposeLayoutinside hot paths and lazy items; prefer standard modifiers,Modifier.layout, orLayoutModifierNode.Intrinsic Measurements: Use intrinsic measurements judiciously and avoid deeply nested intrinsic chains.
3. Lazy layouts optimization (references/lazy-layouts.md)
MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/lazy-layouts.md.
Lazy Layout Scope Guard : Directives for
keyandcontentTypeapply strictly to Lazy containers (LazyColumn,LazyRow,LazyGrid). Never flag standard non-lazy containers (Column,Row,Box) iterating over collections.Mandatory
contentTypeand Primitivekey: Always specify both primitivekeys (Int,Long,String) andcontentTypes for all items in lazy layouts (LazyColumn,LazyRow,LazyGrid). When usingitemsoritemsIndexed, never omitcontentType:contentType = { _, item -> item.type }. OmittingcontentTypeprevents Compose from reusing composition slots during scrolling.In-Item Index Lookups : Replace
list.indexOf(item)withitemsIndexedto eliminateO(N²)lookups during layout passes.Observable Selection & State Queries : Convert selection tracking from
mutableStateListOfto an immutableSetinMutableState(mutableStateOf(emptySet<String>())),mutableStateSetOf(), or Map forO(1)lookups. Pass lambda providers (isSelected: () -> Boolean) to leaf composables to isolate recomposition from parentitemsscopes.Propagate CompositionLocals in Lazy Items : Avoid querying
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.Defer Shared Transitions in Lazy Items : Put
Modifier.sharedBoundsorModifier.sharedElementon lazy items behind visibility indicators (such asModifier.onVisibilityChangedor viewport visibility checks) so offscreen or pre-fetched items do not instantiate transition scopes.Item Count Derivations : Read collection
.sizedirectly instead of wrapping list counts inderivedStateOf.Small & Bounded Lists : Use standard
RoworColumnwithfororforEachloops for small or bounded collections (e.g. 1 to 10 items) to eliminate lazy virtualization, measuring, and pre-fetching overhead.Hoist Shared Flows : Collect shared
Flows once in the parent container preceding lazy layouts; never callcollectAsStateWithLifecycle()per visible item.Avoid Side Effects in Pre-Fetched Items : Never trigger analytics in
LaunchedEffect(Unit)inside lazy items; useModifier.onVisibilityChangedwith dwell thresholds instead.
4. Animation and shared transitions (references/animation.md)
MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/animation.md.
Phase Deferral for Animated Properties : Wrap fast-changing animated state reads (alpha, scale, rotation, color) in
Modifier.graphicsLayer { ... }to bypass Composition and evaluate directly in the Draw phase.Phase Deferral for Offsets & Size : Wrap animated offsets in
Modifier.offset { IntOffset(...) }and animate constraints usingModifier.layout { ... }orModifier.animateBoundsto bypass recomposition during size transitions.Defer Shared Transitions in Fast-Scrolling Lists : Attach
Modifier.sharedBoundsorModifier.sharedElementonly when visible usingModifier.onVisibilityChangedto avoid modifier and observation instantiation costs on discarded pre-fetched items.Lambda Providers : Pass lambda providers (
() -> Float) instead of raw animated values to child composables to keep state reads deferred to Draw or Layout.Persistent
Animatablein Nodes : StoreAnimatableas a persistent member property onModifier.Nodeand launch inonAttach()usingcoroutineScope.launch.
5. Effects, lifecycle, and threading (effects-and-threading.md)
MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/effects-and-threading.md.
Prohibit Direct Side-Effects in Body : Never perform side-effects directly in the Composable body during composition; wrap them in
SideEffect,LaunchedEffect, or user event callbacks.Prohibit Non-Suspending
LaunchedEffect& EmptyDisposableEffect: Never useLaunchedEffectfor synchronous operations (e.g. logging views or updating objects). Never useDisposableEffectwith an emptyonDispose {}block as a workaround. UseSideEffectinstead (in Compose 1.12+,SideEffect(keys) { ... }supports keys directly; on Compose< 1.12,SideEffecttakes no arguments, so check the project's Compose version and track key changes with aremembered holder insideSideEffect { ... }).Cache Allocations in Body : Wrap heavy object allocations (such as date formatters or complex paths) and expensive computations in
remember.Combine Related
LaunchedEffects : Combine multipleLaunchedEffect(Unit)calls into a singleLaunchedEffectwith nestedlaunch { ... }blocks to reduce effect node allocations and coroutine launcher overhead.Effect Ordering & Teardown Costs : Understand effect execution order when composition changes are applied (
DisposableEffectruns first, thenSideEffect, whileLaunchedEffectlaunches a coroutine on the composition'sCoroutineContextthat is dispatched asynchronously and is not guaranteed to wait until after Draw). Note that canceling aLaunchedEffectincurs coroutine cancellation and teardown overhead; avoid cyclingLaunchedEffectkeys frequently during animations or scrolling.Main Thread Offloading : Offload blocking I/O, heavy file parsing, and database operations to
withContext(Dispatchers.IO)usingproduceState.No Item-Level Impression Effects in Lazy Layouts : Never use
LaunchedEffectorDisposableEffectinside lazy items for impression logging. Lazy items are pre-composed before entering the viewport, causing premature or false impressions. UseModifier.onVisibilityChangedwith dwell thresholds instead.Lifecycle-Aware Flow Collection : Use
collectAsStateWithLifecycle()for UI Flow collections that actively produce background work on Android, andcollectAsState()for lightweight in-memory StateFlows or non-Android scopes.Hoist Receivers & Listeners : Register system listeners and
BroadcastReceivers once at the screen level usingDisposableEffect, not inside lazy list items.Guard Optional Effects : Guard effects with
if (callback != null)before launching to prevent allocating empty coroutines and effect nodes.Prevent Stale Captures : Use
rememberUpdatedStatewhen long-running or looping coroutines inLaunchedEffectreference callbacks or parameters.Replace Legacy Timers : Replace
Handler.postDelayedorTimerTaskwithLaunchedEffectanddelay().
6. Graphics and custom drawing (references/graphics-performance.md)
MANDATORY : Before flagging or fixing any issue in this category, you MUST read references/graphics-performance.md.
Cache Drawing Allocations : Replace decorative
Canvasnodes withModifier.drawWithCacheto cachePath,Paint, andBrushallocations.Prefer AsyncImage instead of Image : Use Coil's
AsyncImagefor loading images from the internet andpainterResourcefor drawables.Imageis not optimized for caching and loading images and may cause performance issues.Scope Fast-Changing Uniforms :
remembertheRuntimeShaderandShaderBrushin composition, update size uniforms indrawWithCache, and per-frame uniforms inonDrawBehind.Graphics Path Object Reuse : Prefer
Path.rewind()overreset()in hot draw loops to retain allocated buffers without reallocation.Value Classes & Primitive Collections : Avoid generic tuples (
Pair,Triple) and generic sets (HashSet<Long>); useandroidx.collection.MutableLongSetandandroidx.compose.ui.util.packInts.
7. Custom modifiers: Modifier.Node (Custom modifiers guide)
Modifier.Node Migration : Migrate legacy
Modifier.composedtoModifierNodeElement+Modifier.Node(orDelegatingNodewhen delegating to sub-nodes such asSuspendingPointerInputModifierNode) with capability interfaces (DrawModifierNode,LayoutModifierNode,SemanticsModifierNode,CompositionLocalConsumerModifierNodeusingcurrentValueOf(...)) 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) } }<br />
On-Demand Coordinates : Query
requireLayoutCoordinates()on demand inside pointer or draw handlers inModifier.Noderather than implementingGlobalPositionAwareModifierNode.onGloballyPositioned.
IMPORTANT : For more examples on how to migrate common modifiers to Modifier.Node, you must read Create custom modifiers with Modifier.Node.
Files
- ATTRIBUTION.mdAdded by AutoGineer1010 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md20.5 KiB
- references/android/develop/ui/compose/custom-modifiers.md26.7 KiB
- references/android/develop/ui/compose/performance/backwards-write.md12.0 KiB
- references/android/develop/ui/compose/performance/stability/strongskipping.md6.6 KiB
- references/animation.md8.0 KiB
- references/effects-and-threading.md17.3 KiB
- references/graphics-performance.md9.4 KiB
- references/layouts.md8.8 KiB
- references/lazy-layouts.md12.5 KiB
- references/state-and-stability.md27.5 KiB
references/state-and-stability.md
1. Phase deferral and lambdas (Composition versus Layout versus Draw)
Defer reading animated, frequently changing, or scroll-driven state values until the Layout or Draw phase by wrapping reads in lambdas. This bypasses the expensive Composition phase entirely and avoids unnecessary recompositions.
A. Modifier offsets
Bad (Recomposes on every pixel change):
val offset = scrollState.value Box(modifier = Modifier.offset(x = offset.dp, y = 0.dp))<br />
Optimized (Skips Composition, goes straight to Layout):
Box(modifier = Modifier.offset { IntOffset(scrollState.value, 0) })<br />
B. Alpha and rotation animations
Bad (Recomposes on every animation frame):
val alpha by animateFloatAsState(targetValue) Box(modifier = Modifier.alpha(alpha))<br />
Optimized (Skips Composition and Layout, goes straight to Draw):
val alpha by animateFloatAsState(targetValue) Box(modifier = Modifier.graphicsLayer { this.alpha = alpha })<br />
C. Custom composable parameters
Passing a lambda provider (valueProvider: () -> Float) is beneficial only when
the value is read in Layout or Draw. If read in Composition, pass the raw value
directly to avoid lambda allocation overhead.
Read in Composition (Pass value directly):
@Composable fun TitleText(text: String) { Text(text = text) }<br />
Read in Layout or Draw (Pass lambda provider):
@Composable fun FadingBox(alphaProvider: () -> Float) { Box(Modifier.graphicsLayer { alpha = alphaProvider() }) }<br />
2. Preventing backwards writes across frame phases
A backwards write occurs whenever a Compose State is modified in a later
frame phase (or in a downstream composable scope within the same composition
pass) than where it was read.
Compose executes frames in three strictly forward-flowing phases: Composition > Layout > Drawing. Modifying state in a later phase (or after reading it) forces Compose to schedule an earlier phase to re-run, creating an unoptimized recomposition loop.
Consequences
Extra Frames & Dropped Frames: Forces redundant composition passes across consecutive frames, wasting CPU/GPU resources and dropping frames.
First-Frame Correctness Issues: Initial frames render with invalid, default, or unsettled data (such as zero size or an incorrect offset), causing visible layout popping or flashing when the second frame renders.
Infinite Recomposition Loops: Occurs when layout sizing or draw logic continuously writes back to state that drives composition.
Core rules
Verify Read-Before-Write Order : A backwards write strictly requires a state read to precede the state write (
Read -> Writein the same composition pass, orComposition Read -> Layout or Draw Writeacross frame phases). State writes belong in event callbacks (onClick), coroutines (LaunchedEffect), or side effects (SideEffect); layout callbacks (onSizeChanged,onPlaced) do not count as events.Do Not Confuse
Write -> Readwith Backwards Writes : Assigning to aMutableStateat the top of a composable before any read of that state occurs (or writing in Composition and reading later in theCanvasDraw phase) is not a backwards write, because no read observer has recorded the current composition scope prior to the write (andComposition Write -> Draw Readflows forward). Instead, classifyvar x by remember { mutableStateOf(...) }; x = getValue()as Redundant State Wrapping (unnecessaryMutableStateand slot table allocation that is also fragile if someone later adds a read preceding the write) and replace it with a plainvalor read directly in the target phase.Never write to state in
onSizeChanged,onPlaced, orLayoutModifierif read in Composition : Read sizes directly in Draw or Layout phase (Modifier.drawWithCache,Modifier.layout), hoist window-level sizing (WindowWidthSizeClass), or useFlowRow/LazyVerticalGrid.Never mutate state after reading it in Composition : Use
rememberUpdatedStatewhen you need to capture a changing value in composition without triggering recomposition.Defer state reads to the latest possible phase: Reading state in Layout or Draw skips Composition entirely when the state changes.
Common patterns: backwards writes versus event-driven updates
A. Direct mutation in Composition (Read -> Write versus Write -> Read)
Bad (
Read -> Write: Mutating state after reading it triggers immediate recomposition loop):@Composable fun BadCounter() { var count by remember { mutableIntStateOf(0) } Text("Count: $count") // 1. State read in Composition Button(onClick = {}) { // 2. State write in Composition AFTER read (Backwards write!) count++ } }<br />
Not a Backwards Write, but Redundant/Fragile (
Write -> Readin Composition):// NOT a backwards write because the write happens BEFORE any read in // Composition (and before Canvas reads it in the Draw phase). // However, wrapping a synchronous value in mutableStateOf is redundant // and error-prone if a read is later added before the write. @Composable fun RedundantStateWrapper(viewModel: MyViewModel) { var path by remember { mutableStateOf(Path()) } // 1. Write occurs first (no prior read in scope) path = viewModel.getPath() Canvas(Modifier.fillMaxSize()) { // 2. Read occurs later in Draw phase (Forward flow) drawPath(path, Color.Red) } } // Optimized: Remove redundant mutableStateOf wrapper and read in Draw @Composable fun OptimizedWrapper(viewModel: MyViewModel) { Canvas(Modifier.fillMaxSize()) { val path = viewModel.getPath() drawPath(path, Color.Red) } }<br />
B. Reading in Composition, writing in Layout (phase backwards write)
Bad (Layout writes to state read in Composition, causing first-frame popping):
@Composable fun BadLayout() { var componentHeight by remember { mutableStateOf(0.dp) } // Composition reads state before Layout measures it if (componentHeight > 100.dp) { Banner() } Box( modifier = Modifier.onSizeChanged { size -> // Backwards write: Layout -> Composition componentHeight = size.height.dp } ) }<br />
Optimized (Defer sizing to Layout phase or hoist to Window level):
@Composable fun OptimizedLayout(modifier: Modifier = Modifier) { // Measurement and placement handled in Layout without recomposition Box( modifier = modifier.layout { measurable, constraints -> val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.placeRelative(0, 0) } } ) }<br />
For more information, see the Backwards Write documentation.
3. State and snapshot optimizations
A. Optimize whole-collection updates with neverEqualPolicy()
mutableStateListOf tracks every individual element mutation through the
snapshot system. When fine-grained element tracking is not needed, back your
collection with a standard MutableList wrapped in mutableStateOf(list, neverEqualPolicy()) and trigger recomposition using a load-bearing assignment
(state.value = list).
class ActiveQueueManager {
private val list = mutableListOf<Item>()
val items = mutableStateOf(list, neverEqualPolicy())
fun enqueue(item: Item) {
list.add(item)
items.value = list // Load-bearing assignment triggers recomposition
}
}<br />
B. Use SnapshotStateList.toList() for repeated queries and iterations
Iterating or querying a SnapshotStateList (or SnapshotStateMap) repeatedly
inside a composable registers snapshot read observations on each accessed index
or element.
When performing repeated queries (such as checking .contains() in a loop),
filtering, sorting, or multi-step processing on a snapshot collection, take an
atomic snapshot using .toList() (or .toSet() / .toMap()) once at the start
of the scope and perform operations on that read-only snapshot:
Bad (Repeated contains queries inside loop register fine-grained dependencies on every element):
@Composable fun ItemSelector( items: List<Item>, selectedIds: SnapshotStateList<String>, ) { Column { items.forEach { item -> // Avoid: Repeatedly querying the snapshot list inside the loop val isSelected = selectedIds.contains(item.id) ItemRow(item = item, isSelected = isSelected) } } }<br />
Optimized (Take a read-only snapshot Set once for
O(1)queries):@Composable fun ItemSelector( items: List<Item>, selectedIds: SnapshotStateList<String>, ) { // Convert to a local Set once per recomposition for fast O(1) lookups val selectedSet = selectedIds.toSet() Column { items.forEach { item -> val isSelected = selectedSet.contains(item.id) ItemRow(item = item, isSelected = isSelected) } } }<br />
C. Extract repeated state reads into local variables
Reading Compose State properties (such as transition.currentState,
scrollState.value, or state.value) multiple times in a function registers
redundant snapshot lookups. Cache the state read into a local variable at the
top of the block.
Bad (Repeated snapshot state reads):
val label = when (transition.currentState) { State.Idle -> "Idle" State.Running -> "Running: ${transition.currentState}" State.Finished -> "Finished: ${transition.currentState}" }<br />
Optimized (Single read cached in local variable):
val currentState = transition.currentState val label = when (currentState) { State.Idle -> "Idle" State.Running -> "Running: $currentState" State.Finished -> "Finished: $currentState" }<br />
D. Use computedStateOf versus derivedStateOf (Compose 1.13+)
When deriving state from frequently changing inputs (such as checking
scrollState.value > 0 on every scroll tick), reading the raw state directly in
composition invalidates the composable on every frame.
In Compose 1.13+, computedStateOf is introduced alongside
derivedStateOf:
computedStateOf: Computes its calculation on every read without caching the value.First read : Slightly faster than
derivedStateOfbecause it avoids cache initialization and snapshot dependency bookkeeping.Second read : Slightly slower than
derivedStateOfbecause it re-executes the calculation.Read-after-write (invalidation) : Significantly faster than
derivedStateOfbecause it does not have the expensive cache invalidation path, cache write-back, and snapshot apply-listener dispatch.
derivedStateOf: Caches the result of its calculation and returns the cached value as long as dependency states have not changed.Has a slower invalidation path when its dependency states change frequently, due to cache clearing, re-computation, cache write-back, and advancing snapshots or triggering apply listeners.
When to use which
Prefer
computedStateOf(Compose 1.13+) orremember { derivedStateOf { ... } }(Compose < 1.13) for simple condition checks, boolean flags, or lightweight derivations driven by fast-changing states (such as scroll offsets or slider positions). Checkgradle/libs.versions.tomlorbuild.gradle(.kts)for the project's Compose version before usingcomputedStateOf:@Composable fun ScrollToTopButton(scrollState: ScrollState) { // Compose 1.13+: Invalidates composition only when > 0 changes, // with minimal invalidation overhead compared to derivedStateOf. // On Compose < 1.13, use remember { derivedStateOf { ... } }. val showButton by remember { computedStateOf { scrollState.value > 0 } } if (showButton) { FloatingActionButton(onClick = { /* ... */ }) { Icon(Icons.Default.ArrowUpward, "Scroll to Top") } } }<br />
Use
derivedStateOfwhen the calculation itself is computationally heavy and is read multiple times across the composition pass, so that the benefits of multi-read caching outweigh the invalidation cost.Read frequency nuance for trivial calculations :
derivedStateOfcan also outperformcomputedStateOffor trivial calculations if read frequently enough per composition pass. Specifically,derivedStateOfstarts to make up for the invalidation cost for trivial calculations when read about10 / numberOfStatesReadPerCalculationtimes per composition (assuming the calculation never invalidates between reads).
Prefer plain Kotlin getters (
get()) for trivial property lookups or inverted booleans where invalidation dampening is not needed:var isLocked by mutableStateOf(false) val isReady: Boolean get() = !isLocked<br />
Avoid
produceState+snapshotFlowfor synchronous derivations: WrappingsnapshotFlowinproduceStateadds unnecessary coroutine allocation, context switching, and flow dispatch overhead compared tocomputedStateOforderivedStateOf.Bad (Unnecessary coroutine and flow dispatch):
val isScrolledToTop by produceState(initialValue = true, scrollState) { snapshotFlow { scrollState.firstVisibleItemIndex == 0 } .collect { value = it } }<br />
Optimized (Synchronous snapshot derivation):
// Compose 1.13+: val isScrolledToTop by remember { computedStateOf { scrollState.firstVisibleItemIndex == 0 } } // Compose < 1.13: val isScrolledToTop by remember { derivedStateOf { scrollState.firstVisibleItemIndex == 0 } }<br />
4. Strong skipping mode and stability
Don't annotate everything with @Stable or @Immutable (or wrap collections
in ImmutableList) in an attempt to force every composable to skip.
Skipping a composable is not free. Forcing stability can actually degrade runtime performance instead of improving it.
A. How Compose handles skipping under the hood
When a composable is made skippable, the Compose compiler generates slot table storage and comparison logic for every parameter:
// What you write
@Composable
fun ContactCell(contact: Contact) {
/* Your function body */
}
// What the Compose compiler generates (simplified)
@Composable
fun ContactCell(
contact: Contact,
$composer: Composer?,
$changed: Int
) {
val $dirty = $changed or $composer.changed(contact)
if ($dirty) {
/* Your function body */
} else {
$composer.skipToGroupEnd()
}
}Every parameter passed to a composable is effectively stored in the slot table
as if it were remembered. On every recomposition pass:
Compose reads the previous parameter value from the slot table.
It executes an equality check between the old and new parameter values.
If any check fails, the composable executes its body; if all checks pass, it calls
$composer.skipToGroupEnd().
This slot table caching and comparison logic incurs memory and CPU overhead on every recomposition attempt.
B. Instance equality (===) versus structural equality (.equals())
Under Strong Skipping Mode (enabled by default in modern Compose):
Unstable parameters are compared using instance equality (
===/$composer.changedInstance(param)).Stable parameters (primitives,
@Stable/@Immutableannotated classes, or types with all stable properties) are compared using structural equality (.equals()/$composer.changed(param)).
Why @Stable, @Immutable, and ImmutableList can hurt performance
Unstable parameters are not prevented from skipping: if the same instance is
passed across recompositions (param === oldParam), Compose skips the
composable quickly with a fast O(1) pointer check.
When you annotate a class with @Stable or @Immutable (or replace
kotlin.collections.List with ImmutableList), Compose switches from fast
=== pointer comparison to deep .equals() structural comparison.
Expensive Deep Comparisons : In complex models or large collections (e.g. hundreds of items), running
equals()on every recomposition can be far more expensive than executing the composable's body. Method traces often reveal thatModel.equalsconsumes the vast majority of frame time.Composition Counts != Benchmarks : A composable that skips but spends 3ms evaluating a deep
.equals()check is significantly slower than a composable that recomposes in 0.2ms.Never Recommend Replacing
List<T>withImmutableList<T>: Never recommend convertingkotlin.collections.List<T>properties intokotlinx.collections.immutable.ImmutableList<T>(or GuavaImmutableListviastability_config.txt) on@Stableor@Immutablemodels. StandardList<T>already skips viaO(1)reference equality (===) under Strong Skipping Mode, whereasImmutableList<T>forcesO(N)element-by-element.equals()traversal.
Scope guard: when to remove existing @Stable or @Immutable
When auditing or refactoring an existing codebase, apply a strict scope guard before recommending changes to existing stability annotations:
Only Recommend Removing
@Stable/@Immutablefor Large Datasets in Lazy Layouts : Strongly recommend removing existing@Stableor@Immutableannotations from data models only when both conditions apply:The model is used within a lazy layout (
LazyColumn,LazyRow,LazyVerticalGrid,LazyHorizontalGrid,Pager,ScalingLazyColumn) as the input collection container or item model, ANDIt holds a large dataset or deep nested collection tree (such as a full screen stream, hundreds of items/tags, or nested lists like
PostcontainingList<Paragraph>andList<Markup>), whereO(N)structural equality checks during scrolling or recomposition are expensive.
Leave Existing Annotations Untouched Elsewhere : For all other use cases where a codebase already has
@Stable,@Immutable, orImmutableList--- such as non-lazy screen/component models, standalone UI elements, or models with small/bounded collections (e.g. a card model holding 2--5 badges, thumbnails, or metadata rows) where dataset size is small or hard to estimate statically---leave the existing annotations untouched.
C. Parameter unwrapping and equality propagation pitfall (ImmutableList)
The Compose compiler includes an optimization where propagating the exact same object reference down the composable hierarchy allows Compose to reuse previous equality results and skip redundant comparisons.
When a parent @Composable passes the exact same parameter reference to a child
@Composable, the Compose compiler propagates its dirty bitmask so the child
can skip re-evaluating .equals().
However, when a parent @Composable receives a data class containing a large
ImmutableList and passes the unwrapped ImmutableList to a child
@Composable, Compose runs O(N) structural equality twice:
// Bad: Both HomeScreen (via data class .equals()) and HomeContent evaluate
// O(N) structural equality on the same ImmutableList in a single frame
data class HomeScreenModel(
val header: String,
val items: ImmutableList<ItemModel>
)
@Composable
private fun HomeScreen(model: HomeScreenModel) {
TopAppBar(title = { Text(model.header) })
// Unwrapping model.items to pass to a child @Composable
HomeContent(model.items)
}
// Because contentList is an ImmutableList, HomeContent must re-evaluate O(N)
// .equals() on the list itself, even though HomeScreen already compared model
@Composable
private fun HomeContent(contentList: ImmutableList<ItemModel>) {
LazyColumn {
items(contentList) { /* ... */ }
}
}<br />
In the preceding example, because items is an ImmutableList (which the
compiler treats as stable and compares with .equals()) inside a data class:
HomeScreenevaluatesmodel.equals(oldModel), which traversesmodel.items.equals(oldModel.items)inO(N)time.HomeContentreceivesmodel.itemsrather thanmodel, so the compiler cannot propagatemodel's$dirtyflag and callscontentList.equals(oldContentList)a second time (O(N)).
Scope guard: when parameter unwrapping is not an issue
Do not flag parameter unwrapping unless all of the following conditions are met:
Both caller and callee are skippable
@Composablefunctions : Plain Kotlin functions, node-building helpers, andLazyListScope/LazyGridScopeDSL extensions (for example,fun verticalGridUi(itemList = content.itemList, ...)) are not skippable composables and do not generate$composer.changed(...)equality checks in the slot table.The parent object is a
@Composableparameter with structural.equals(): If the container object is read from state inside the function body (such asval content = model.contentState.value) rather than passed as a@Composableparameter, or is a regularclasswithout a deepdata class.equals()implementation, no parent equality check occurred in the first place.The unwrapped property itself triggers expensive
O(N).equals(): The unwrapped property must be anImmutableList(or a collection marked stable instability_config.txt). Never flag unwrapping a standardkotlin.collections.List<T>(Set<T>,Map<K, V>) or primitive/value-type properties (Int,Dp,String,Boolean, enums)---under Strong Skipping Mode, standardList<T>is compared viaO(1)reference equality (===), so unwrappingcontent.itemList: List<T>has zero deep-comparison overhead.
D. Don't over-index on recomposition counts
Recomposition counts are not a substitute for benchmarks. Once composition is
scheduled for a screen, skipping a single intermediate composable saves minimal
time while still incurring the overhead of remembering parameters and evaluating
equality checks. Rather than trying to eliminate every individual recomposition,
focus on avoiding unnecessary compositions altogether by deferring rapidly
changing state reads to the Layout or Draw phases (for example, using lambda
modifiers and graphicsLayer), and
keep composables lightweight so they execute quickly when recomposition
occurs.
E. Guidelines for designing fast composables
Prefer fewer, easy-to-compare arguments : Pass primitives (
String,Int,Long,Dp) or standardList<T>references (which compare via fast===) rather than large composite objects whenever practical.Avoid double
O(N)comparisons onImmutableList: Do not wrap large collections inImmutableListinsidedata classmodels where both parent and child@Composablefunctions will runO(N).equals()on the list; use standardList<T>so Compose usesO(1)===reference equality.Merge related effects and state: Minimize the number of remembered objects and dispatched effects to reduce slot table overhead.
Be selective with
@Stable/@Immutable: Only add@Stableor@Immutableto small, flat UI models from non-Compose modules where instances are frequently recreated and.equals()is cheapO(1). Never add@Stable,@Immutable, orImmutableListto large collections or deep data graphs. When auditing existing code, only remove@Stableor@Immutablefrom models that feed lazy layouts (LazyColumn,LazyRow,LazyGrid) with large datasets or deep nested collections; leave existing annotations on non-lazy or small-collection models untouched.Always benchmark: Use Macrobenchmark or Microbenchmark to measure real frame timing and CPU impact. Never rely solely on recomposition counts to judge performance.
Optimized (Remove
@Immutableon large lazy-layout models to rely on fast===instance equality, and pass lightweight primitives):// Unstable model skips using === pointer check when instance is unchanged data class FeedState( val feedId: String, val items: List<FeedItem> ) @Composable fun FeedScreen(state: FeedState) { // Pass only the primitive ID needed by the header FeedHeader(feedId = state.feedId) // Pass the state or items directly FeedList(items = state.items) }<br />
For more information, see the Strong Skipping Mode documentation.
5. Using remember and calculation keys
While remember is essential for preserving state and caching expensive
operations across recompositions, each call stores its result and keys in the
slot table and checks key equality on every recomposition. Use remember when
object identity must be preserved or when caching nontrivial work (such as
formatters, shaders, paths, or list transformations), rather than wrapping
trivial expressions or cheap allocations whose key comparisons cost more than
the allocation itself.
Require explicit calculation keys on remember
remember { ... } with no keys executes only on initial composition and caches
the result for the lifetime of the Composable. If the Composable recomposes with
new parameter values, omitting keys returns the stale cached value. For standard
Kotlin calculations and object instantiations, always pass every external
variable or parameter referenced inside the remember block as a key.
Exception for
derivedStateOf: When wrappingderivedStateOf, do not pass the snapshot state properties read inside the calculation lambda asrememberkeys:// Bad: passing snapshot state property as a key breaks derivedStateOf val showButton by remember(scrollState.firstVisibleItemIndex) { derivedStateOf { scrollState.firstVisibleItemIndex > 0 } } // Optimized: derivedStateOf tracks firstVisibleItemIndex internally val showButton by remember { derivedStateOf { scrollState.firstVisibleItemIndex > 0 } }<br />
derivedStateOfdynamically tracks snapshot state reads internally and invalidates only when the derived result actually changes. Passing state values asrememberkeys forces therememberblock to recreate on every single state mutation, completely destroyingderivedStateOf's ability to skip recompositions. Only pass theStateholder instance as a key if the instance itself can change.Bad (Omitting keys for standard calculation returns stale value upon parameter change):
@Composable fun FormattedDateLabel(timestamp: Long, locale: Locale) { val formattedDate = remember { SimpleDateFormat("yyyy-MM-dd", locale).format(Date(timestamp)) } Text(text = formattedDate) }<br />
Optimized (Pass referenced calculation parameters as keys):
@Composable fun FormattedDateLabel(timestamp: Long, locale: Locale) { val formattedDate = remember(timestamp, locale) { SimpleDateFormat("yyyy-MM-dd", locale).format(Date(timestamp)) } Text(text = formattedDate) }<br />
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Google LLC
- Publisher
- Android (Google) (Official)
- Distributed by
- Android (Google)
- Source
- android/skills · jetpack-compose/jetpack-compose-performance · commit bf68e2d
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.txt)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Google LLC or Android (Google).
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download jetpack-compose-performance.zip