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 function, 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 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.
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 or ) 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 (, 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 ( or Composition 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 () : 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 snapshot overhead (and risks becoming a backwards write if a read is later added preceding the assignment); use a plain local or read the value directly inside the target phase (such as ).
- Explicit Keys & Slot Overhead : Always pass all input variables and composable parameters referenced inside as calculation keys. Remember that stores objects in the slot table and checks key equality on every recomposition; only when allocations are heavy or identity must be preserved. Do not pass snapshot state values/properties (e.g. ) as keys when wrapping (passing the instance itself is fine if the instance reference can change).
- vs (Compose 1.13+) : On Compose 1.13+, use for simple condition checks and filtered state from fast-changing inputs (such as ), which provides significantly faster invalidation than (on Compose , use
remember { derivedStateOf { ... } }
). Reserve 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.
- Synchronous State Derivation : Audit for asynchronous + blocks observing Compose states (such as scroll positions or collection sizes); replace them with synchronous
remember { derivedStateOf { ... } }
(or on Compose 1.13+).
- Trivial Primitives : Prefer plain custom Kotlin getters () over or for simple boolean expressions and property lookups.
- Collection State Tracking : Back whole-list updates with standard and
mutableStateOf(list, neverEqualPolicy())
with load-bearing assignments instead of .
- Snapshot Collections : Use
SnapshotStateList.toList()
for repeated queries or iterations to avoid per-element read observation overhead.
- Repeated State Reads : Extract repeated Compose property reads into a local variable at the top of the block.
- State in Setters : Avoid reading Compose inside 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 , , or 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 ) when instance equality () matches. Annotating models or using forces structural equality (), which can be significantly more expensive than recomposition itself for large collections or complex classes.
- Never Add , , or to Collection
Models : When writing or optimizing code, never add or to models containing collections (, , ), and never recommend replacing
kotlin.collections.List<T>
with (or adding to ). Calling on collections on every recomposition pass is more expensive than instance equality () under Strong Skipping Mode.
- Scope Guard for Removing Existing / Annotations
(Large Lazy Datasets Only) :
- When to Remove : Only recommend removing existing or annotations from data models when both conditions are met: (1) the model is used within a lazy layout (, , , , ) 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 with and ), where recursive checks degrade scrolling and recomposition performance.
- When to Leave Untouched : For all other existing , , or 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 / classes across a codebase without verifying they feed a lazy layout with a large dataset.
- When to Add / Under Strong Skipping Mode : Flat es with primitive/ properties in Compose modules are already inferred as stable by the compiler and use automatically---do not add redundant annotations to them. Only add or 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 (, , ), and its check is trivial .
- 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 (leaving the house 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 ; use
Modifier.onVisibilityChanged
for viewport tracking, or Modifier.onLayoutRectChanged
for local bounds, and query requireLayoutCoordinates()
on demand inside event handlers.
- Anchor Floating Content via Custom : When attaching floating labels or tooltips to a component, use a custom measuring and placing both children relative to each other. Never track coordinates in to position floating content with , 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 es and decorative nodes; attach modifiers directly or use .
- Subcomposition Overhead : Avoid / inside hot paths and lazy items; prefer standard modifiers, , or .
- 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 and apply strictly to Lazy containers (, , ). Never flag standard non-lazy containers (, , ) iterating over collections.
- Mandatory and Primitive : Always specify both primitive s (, , ) and s for all items in lazy layouts (, , ). When using or , never omit :
contentType = { _, item -> item.type }
. Omitting prevents Compose from reusing composition slots during scrolling.
- In-Item Index Lookups : Replace with to eliminate lookups during layout passes.
- Observable Selection & State Queries : Convert selection tracking from to an immutable in (
mutableStateOf(emptySet<String>())
), , or Map for lookups. Pass lambda providers (isSelected: () -> Boolean
) to leaf composables to isolate recomposition from parent scopes.
- Propagate CompositionLocals in Lazy Items : Avoid querying s (, ,
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 or 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.
- Item Count Derivations : Read collection directly instead of wrapping list counts in .
- Small & Bounded Lists : Use standard or with or loops 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 s once in the parent container preceding lazy layouts; never call
collectAsStateWithLifecycle()
per visible item.
- Avoid Side Effects in Pre-Fetched Items : Never trigger analytics in inside lazy items; use
Modifier.onVisibilityChanged
with 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 using or to bypass recomposition during size transitions.
- Defer Shared Transitions in Fast-Scrolling Lists : Attach or only when visible using
Modifier.onVisibilityChanged
to avoid modifier and observation instantiation costs on discarded pre-fetched items.
- Lambda Providers : Pass lambda providers () instead of raw animated values to child composables to keep state reads deferred to Draw or Layout.
- Persistent in Nodes : Store as a persistent member property on and launch in using .
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 , , or user event callbacks.
- Prohibit Non-Suspending & Empty : Never use for synchronous operations (e.g. logging views or updating objects). Never use with an empty block as a workaround. Use instead (in Compose 1.12+, supports keys directly; on Compose , takes no arguments, so check the project's Compose version and track key changes with a ed holder inside ).
- Cache Allocations in Body : Wrap heavy object allocations (such as date formatters or complex paths) and expensive computations in .
- Combine Related s : Combine multiple calls into a single with nested blocks to reduce effect node allocations and coroutine launcher overhead.
- Effect Ordering & Teardown Costs : Respect effect execution order ( > > Layout and Draw > after frame). Note that canceling a incurs coroutine cancellation and teardown overhead; avoid cycling keys frequently during animations or scrolling.
- Main Thread Offloading : Offload blocking I/O, heavy file parsing, and database operations to
withContext(Dispatchers.IO)
using .
- No Item-Level Impression Effects in Lazy Layouts : Never use or 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.
- Lifecycle-Aware Flow Collection : Use
collectAsStateWithLifecycle()
for UI Flow collections that actively produce background work on Android, and for lightweight in-memory StateFlows or non-Android scopes.
- Hoist Receivers & Listeners : Register system listeners and s once at the screen level using , not inside lazy list items.
- Guard Optional Effects : Guard effects with before launching to prevent allocating empty coroutines and effect nodes.
- Prevent Stale Captures : Use when long-running or looping coroutines in reference callbacks or parameters.
- Replace Legacy Timers : Replace or with and .
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 nodes with to cache , , and allocations.
- Prefer AsyncImage instead of Image : Use Coil's for loading images from the internet and for drawables. is not optimized for caching and loading images and may cause performance issues.
- Scope Fast-Changing Uniforms : the and in composition, update size uniforms in , and per-frame uniforms in .
- Graphics Path Object Reuse : Prefer over in hot draw loops to retain allocated buffers without reallocation.
- Value Classes & Primitive Collections : Avoid generic tuples (, ) and generic sets (); use
androidx.collection.MutableLongSet
and androidx.compose.ui.util.packInts
.
7. Custom modifiers: (Custom modifiers guide)
-
Modifier.Node Migration : Migrate legacy
to
+
(or
when delegating
to sub-nodes such as
SuspendingPointerInputModifierNode
) with capability
interfaces (
,
,
,
CompositionLocalConsumerModifierNode
using
) to eliminate per-node subcomposition overhead and
enable node reuse (see
Create custom modifiers with Modifier.Node):
kotlin
// 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 in
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.