Generated banner for Jetpack Compose Performance
Generated logo for Jetpack Compose Performance

Jetpack Compose Performance

Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)

  • Skill
  • Review and audit
  • Software development
  • Apache-2.0
  • No issues found

From the author

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.
— the description by Google LLC

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/android/jetpack-compose-performance/download
  2. Unzip 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:

  1. Release Build: Never profile or benchmark debuggable builds; ART runtime verification severely degrades performance.

  2. R8 Minification: Keep R8 enabled to optimize bytecode and coroutine dispatch.

  3. 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

  1. Exhaustive Scan : Scan the target code against all 7 core categories in the following sections. Evaluate every @Composable function, modifier chain, and lazy-layout data model against all checklist rules rather than stopping after the first issue found.

  2. 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/*.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.

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.offset or Modifier.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, 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.

  • Avoid Redundant State Wrapping in Composition (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).

  • Explicit 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.

  • Synchronous State Derivation : Audit for asynchronous 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+).

  • Trivial Primitives : Prefer plain custom Kotlin getters (get()) over derivedStateOf or computedStateOf for simple boolean expressions and property lookups.

  • Collection State Tracking : Back whole-list updates with standard mutableListOf() and mutableStateOf(list, neverEqualPolicy()) with load-bearing assignments instead of mutableStateListOf().

  • Snapshot Collections : Use SnapshotStateList.toList() for repeated queries or iterations to avoid per-element read observation overhead.

  • Repeated State Reads : Extract repeated Compose State property reads into a local variable at the top of the block.

  • State in Setters : Avoid reading Compose State 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 @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.

  • Never Add @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.

  • Scope Guard for Removing Existing @Stable / @Immutable Annotations (Large Lazy Datasets Only) :

    • When to Remove : Only recommend removing existing @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.

    • When to Leave Untouched : For all other existing @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.

  • When to Add @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).

  • 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; use Modifier.onVisibilityChanged for viewport tracking, Modifier.onPlaced or Modifier.onLayoutRectChanged for local bounds, and query requireLayoutCoordinates() on demand inside Modifier.Node event handlers.

  • Anchor Floating Content via Custom 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.

  • 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 decorative Canvas nodes; attach modifiers directly or use Modifier.drawBehind.

  • Subcomposition Overhead : Avoid BoxWithConstraints / SubcomposeLayout inside hot paths and lazy items; prefer standard modifiers, Modifier.layout, or LayoutModifierNode.

  • 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 key and contentType apply strictly to Lazy containers (LazyColumn, LazyRow, LazyGrid). Never flag standard non-lazy containers (Column, Row, Box) iterating over collections.

  • Mandatory 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.

  • In-Item Index Lookups : Replace list.indexOf(item) with itemsIndexed to eliminate O(N²) lookups during layout passes.

  • Observable Selection & State Queries : Convert selection tracking from 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.

  • 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.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.

  • Item Count Derivations : Read collection .size directly instead of wrapping list counts in derivedStateOf.

  • Small & Bounded Lists : Use standard 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.

  • Hoist Shared Flows : Collect shared Flows 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 LaunchedEffect(Unit) 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 Modifier.layout { ... } or Modifier.animateBounds to bypass recomposition during size transitions.

  • Defer Shared Transitions in Fast-Scrolling Lists : Attach Modifier.sharedBounds or Modifier.sharedElement only when visible using Modifier.onVisibilityChanged to 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 Animatable in Nodes : Store Animatable as a persistent member property on Modifier.Node and launch in onAttach() using coroutineScope.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 & 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 { ... }).

  • Cache Allocations in Body : Wrap heavy object allocations (such as date formatters or complex paths) and expensive computations in remember.

  • Combine Related LaunchedEffects : Combine multiple LaunchedEffect(Unit) calls into a single LaunchedEffect with nested launch { ... } blocks to reduce effect node allocations and coroutine launcher overhead.

  • Effect Ordering & Teardown Costs : Understand effect execution order when composition changes are applied (DisposableEffect runs first, then SideEffect, while LaunchedEffect launches a coroutine on the composition's CoroutineContext that is dispatched asynchronously and is not guaranteed to wait until after Draw). Note that canceling a LaunchedEffect incurs coroutine cancellation and teardown overhead; avoid cycling LaunchedEffect keys frequently during animations or scrolling.

  • Main Thread Offloading : Offload blocking I/O, heavy file parsing, and database operations to withContext(Dispatchers.IO) using produceState.

  • No Item-Level Impression Effects in Lazy Layouts : Never use 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.

  • Lifecycle-Aware Flow Collection : Use collectAsStateWithLifecycle() for UI Flow collections that actively produce background work on Android, and collectAsState() for lightweight in-memory StateFlows or non-Android scopes.

  • Hoist Receivers & Listeners : Register system listeners and BroadcastReceivers once at the screen level using DisposableEffect, 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 rememberUpdatedState when long-running or looping coroutines in LaunchedEffect reference callbacks or parameters.

  • Replace Legacy Timers : Replace Handler.postDelayed or TimerTask with LaunchedEffect and delay().

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 Canvas nodes with Modifier.drawWithCache to cache Path, Paint, and Brush allocations.

  • Prefer AsyncImage instead of Image : Use Coil's 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.

  • Scope Fast-Changing Uniforms : remember the RuntimeShader and ShaderBrush in composition, update size uniforms in drawWithCache, and per-frame uniforms in onDrawBehind.

  • Graphics Path Object Reuse : Prefer Path.rewind() over reset() in hot draw loops to retain allocated buffers without reallocation.

  • Value Classes & Primitive Collections : Avoid generic tuples (Pair, Triple) and generic sets (HashSet<Long>); use androidx.collection.MutableLongSet and androidx.compose.ui.util.packInts.

7. Custom modifiers: 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)
        }
    }

    <br />

  • 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.

Files

references/effects-and-threading.md

1. Main thread blocking, offloading, and caching

Move non-UI work off the main thread, avoid heavy object allocations directly inside Composable bodies, and cache expensive calculations across recompositions using remember.

1. Cache expensive computations in composable body

If a Composable body performs sorting, filtering, or heavy string manipulation on a collection, wrap the calculation in remember:

  • Bad (Recalculated on every recomposition pass):

    @Composable
    fun FilteredFeed(rawList: List<Post>, query: String) {
        // Avoid: Heavy filtering and sorting on every recomposition
        val filteredList = rawList
            .filter { it.title.contains(query) }
            .sortedBy { it.timestamp }
        PostList(posts = filteredList)
    }

    <br />

  • Optimized (Cached calculation using remember):

    @Composable
    fun FilteredFeed(rawList: List<Post>, query: String) {
        val filteredList = remember(rawList, query) {
            rawList
                .filter { it.title.contains(query) }
                .sortedBy { it.timestamp }
        }
        PostList(posts = filteredList)
    }

    <br />

For collections with very few elements (3 to 5 items), wrapping calculations in remember introduces allocation overhead without measurable benefit. Benchmark caching changes using Macro benchmark.

2. Avoid heavy object allocations in composition

Never allocate or compute heavy objects (such as RoundedPolygon, complex paths, Paint, or date formatters) directly in the Composable body. Wrap them in remember { ... } or hoist them out of the Composable.

  • Bad (New date formatter allocated on every frame/recomposition):

    @Composable
    fun DateBadge(timestamp: Long) {
        val formatter = SimpleDateFormat("MMM dd, yyyy", LocalLocale.current.platformLocale)
        Text(text = formatter.format(Date(timestamp)))
    }

    <br />

  • Optimized (Formatter allocated once and reused across timestamp updates):

    // Reusable formatter allocated once at top-level or remembered
    private val dateFormatter =
        SimpleDateFormat("MMM dd, yyyy", Locale.getDefault())
    
    @Composable
    fun DateBadge(timestamp: Long) {
        val formattedDate = dateFormatter.format(Date(timestamp))
    
        Text(text = formattedDate)
    }

    <br />

Conversion functions like .toShape() or painterResource() are @Composable themselves and internally handle caching.

3. Offload I/O and heavy work to Dispatchers.IO with produceState

Never perform blocking operations (like database queries, disk I/O, heavy file parsing, or blocking binder transactions) directly on the main thread. Offload them to Dispatchers.IO using produceState:

  • Bad (Blocking I/O on main UI thread):

    @Composable
    fun ProfileScreen(fileUri: Uri) {
        var state by remember { mutableStateOf<Data?>(null) }
        LaunchedEffect(fileUri) {
            val data = parseJsonFromDisk(fileUri) // Blocks main dispatcher!
            state = data
        }
    }

    <br />

  • Optimized (Offloaded to IO dispatcher via produceState):

    @Composable
    fun ProfileScreen(fileUri: Uri) {
        val state by produceState<Data?>(initialValue = null, fileUri) {
            value = withContext(Dispatchers.IO) { parseJsonFromDisk(fileUri) }
        }
    }

    <br />

2. Side effect execution and lifecycle rules

Structure side effects to be lifecycle-aware, idempotent, and properly scoped. Prohibit direct side-effects in the Composable body, prefer SideEffect for non-suspending operations, hoist flow or receiver subscriptions out of item composables, and always use collectAsStateWithLifecycle().

1. Prohibit direct side-effects in composable bodies

The Composable body must remain idempotent and free of direct side effects. Side effects placed directly in composition run on every recomposition attempt (including speculative, interrupted, or discarded passes).

  • Bad (Side-effect runs directly in composition pass):

    @Composable
    fun UserProfile(userId: String, viewModel: ProfileViewModel) {
        // Avoid: Runs on every recomposition and speculative pass
        viewModel.trackProfileImpression(userId)
        Text(text = "User: $userId")
    }

    <br />

  • Optimized (Wrapped in SideEffect or user event handler):

    @Composable
    fun UserProfile(userId: String, viewModel: ProfileViewModel) {
        // Compose 1.12+: keyed SideEffect
        SideEffect(userId) {
            viewModel.trackProfileImpression(userId)
        }
        Text(text = "User: $userId")
    }

    <br />

2. Prohibit LaunchedEffect for non-suspend operations

Never wrap synchronous, non-suspending operations in LaunchedEffect. LaunchedEffect creates a standalone coroutine, allocates coroutine context machinery, and dispatches to a thread even when no suspension occurs.

  • Bad (Unnecessary coroutine allocation for synchronous call):

    LaunchedEffect(itemId) {
        analyticsTracker.trackScreenView(itemId) // Non-suspend function!
    }

    <br />

  • Optimized (Use SideEffect for synchronous execution on successful composition):

    // Compose 1.12+ (supports keys directly):
    SideEffect(itemId) {
        analyticsTracker.trackScreenView(itemId)
    }

    <br />

  • Warning : Never use DisposableEffect(keys) { ... onDispose {} } with an empty onDispose block to trigger a keyed synchronous effect. Check the project's Compose version in gradle/libs.versions.toml or build.gradle(.kts): use SideEffect(keys) on Compose 1.12+, or SideEffect { ... } with a remembered key check on pre-1.12 versions.

3. Lifecycle-aware flow collection (collectAsStateWithLifecycle)

In Android UI development, use collectAsStateWithLifecycle() when collecting Kotlin Flows that actively produce background work. collectAsStateWithLifecycle (from androidx.lifecycle:lifecycle-runtime-compose) automatically subscribes and cancels flow collection based on the Android Lifecycle state (defaulting to Lifecycle.State.STARTED), preventing background CPU usage, battery drain, resource leaks, and unnecessary UI updates when the app or screen is stopped.

  • Performance Nuance & When to Prefer collectAsState():

    • Benchmark Overhead : collectAsStateWithLifecycle() is ~3-4x slower to subscribe and dispatch compared to collectAsState() due to Android Lifecycle observer registration and lifecycle-aware state machine overhead.

    • In-Memory & Scoped StateFlows : For lightweight, in-memory StateFlows (such as UI states emitted by a ViewModel already scoped with SharingStarted.WhileSubscribed(5000)), collectAsState() is often more performant and avoids this overhead.

    • When to Require collectAsStateWithLifecycle() : Reserve collectAsStateWithLifecycle() for cold flows, database observation streams, sensors, location updates, or external polling streams that must halt emission when the screen is not visible.

    • Non-Android platforms : In Compose Multiplatform (Desktop, Web, iOS) where the Android Lifecycle library is not present, use collectAsState().

    • Headless / Unit Test environments : In non-UI scopes or pure unit tests where no LifecycleOwner is available.

  • Bad (Continues collecting in background on Android, leaking resources and CPU cycles):

    @Composable
    fun HomeFeed(viewModel: FeedViewModel) {
        // Avoid on Android: Flow stays active when activity is stopped
        val uiState by viewModel.feedState.collectAsState()
        FeedContent(uiState = uiState)
    }

    <br />

  • Optimized (Lifecycle-aware: pauses collection when backgrounded):

    // import androidx.lifecycle.compose.collectAsStateWithLifecycle
    
    @Composable
    fun HomeFeed(viewModel: FeedViewModel) {
        val uiState by viewModel.feedState.collectAsStateWithLifecycle()
        FeedContent(uiState = uiState)
    }

    <br />

4. Hoist BroadcastReceivers and listeners to prevent per-item registration

Never register a BroadcastReceiver or system listener (such as ACTION_TIMEZONE_CHANGED or network connectivity changes) inside list item Composables. This registers a separate receiver for every visible item on the main thread, causing severe scrolling latency, memory leaks, and frame drops.

Register a single receiver in a parent or screen-level Composable using DisposableEffect, and propagate the state down using parameters or CompositionLocalProvider.

  • Bad (Registers a separate BroadcastReceiver for every visible item in LazyColumn):

    @Composable
    fun TimeZoneListItem(timeZoneId: String) {
        val context = LocalContext.current
        DisposableEffect(Unit) {
            // Avoid: Multiplied BroadcastReceivers per visible item!
            val receiver = object : BroadcastReceiver() {
                // ...
            }
            context.registerReceiver(
                receiver,
                IntentFilter(Intent.ACTION_TIMEZONE_CHANGED),
            )
            onDispose { context.unregisterReceiver(receiver) }
        }
        ItemRow(timeZoneId)
    }

    <br />

  • Optimized (Single BroadcastReceiver hoisted to parent container):

    @Composable
    fun TimeZoneList(timeZoneIds: List<String>) {
        val context = LocalContext.current
        var currentTimeZone by remember {
            mutableStateOf(TimeZone.getDefault())
        }
    
        DisposableEffect(context) {
            val receiver = object : BroadcastReceiver() {
                override fun onReceive(c: Context?, intent: Intent?) {
                    currentTimeZone = TimeZone.getDefault()
                }
            }
            context.registerReceiver(
                receiver,
                IntentFilter(Intent.ACTION_TIMEZONE_CHANGED),
            )
            onDispose { context.unregisterReceiver(receiver) }
        }
    
        LazyColumn {
            items(timeZoneIds, key = { it }) { id ->
                TimeZoneListItem(
                    timeZoneId = id,
                    currentTimeZone = currentTimeZone,
                )
            }
        }
    }

    <br />

5. Guard optional effects and match effect type to work

Never spawn LaunchedEffect or DisposableEffect unconditionally if optional callbacks or trigger handlers are null. Guard the effect with if (callback != null) to avoid allocating unnecessary coroutine jobs and snapshot effect tracking structures. Furthermore, ensure the effect API matches the execution type:

  • Synchronous Callbacks (() -> Unit) : Use SideEffect or keyed SideEffect(onInit) rather than launching a coroutine job.

  • Suspending Callbacks (suspend () -> Unit) : Use LaunchedEffect(onInit) guarded by if (onInit != null).

  • Bad (Spawns empty coroutine and effect nodes when callback is null or synchronous):

    // Avoid: Launches coroutine for synchronous work, runs even if null
    LaunchedEffect(onInit) {
        onInit?.invoke()
    }

    <br />

  • Optimized (Synchronous work uses SideEffect; guarded if optional):

    if (onInit != null) {
        SideEffect(onInit) {
            onInit()
        }
    }

    <br />

6. Prevent stale captures with rememberUpdatedState

If a long-running, periodic, or looping coroutine inside LaunchedEffect references a Composable parameter or callback, use rememberUpdatedState to ensure it always uses the latest value without restarting the effect:

  • Bad (Stale capture if onTick parameter changes during loop lifetime):

    @Composable
    fun PeriodicTicker(intervalMs: Long, onTick: () -> Unit) {
        LaunchedEffect(intervalMs) {
            while (isActive) {
                delay(intervalMs)
                onTick() // Stale reference if onTick callback instance changes!
            }
        }
    }

    <br />

  • Optimized (rememberUpdatedState provides latest callback without cancelling timer loop):

    @Composable
    fun PeriodicTicker(intervalMs: Long, onTick: () -> Unit) {
        val currentOnTick by rememberUpdatedState(onTick)
        LaunchedEffect(intervalMs) {
            while (isActive) {
                delay(intervalMs)
                currentOnTick()
            }
        }
    }

    <br />

7. Replace legacy timers with coroutine delays

Avoid using legacy Android handlers like Handler.postDelayed or TimerTask in UI code. Use LaunchedEffect combined with delay() for clean, lifecycle-aware timing that is automatically cancelled when the Composable leaves the composition.

  • Bad (Legacy Handler risks memory leak and out-of-lifecycle execution):

    DisposableEffect(Unit) {
        val handler = Handler(Looper.getMainLooper())
        val runnable = Runnable { showBanner = false }
        handler.postDelayed(runnable, 3000L)
        onDispose { handler.removeCallbacks(runnable) }
    }

    <br />

  • Optimized (Clean, lifecycle-aware coroutine delay):

    LaunchedEffect(Unit) {
        delay(3000L)
        showBanner = false
    }

    <br />

Every LaunchedEffect attached to a composable allocates slot table records, registers coroutine launcher machinery, and requires cancellation tracking during teardown.

When multiple asynchronous tasks share the same trigger key (such as Unit on initial screen load), combine them into a single LaunchedEffect block with nested launch { ... } calls instead of declaring multiple standalone LaunchedEffects.

  • Bad (Multiple separate LaunchedEffects incur redundant effect overhead):

    @Composable
    fun ShoppingCartScreen(viewModel: CartViewModel) {
        // Avoid: 3 LaunchedEffects allocate 3 effect nodes and launchers
        LaunchedEffect(Unit) { viewModel.loadCart() }
        LaunchedEffect(Unit) { viewModel.loadPaymentMethods() }
        LaunchedEffect(Unit) { viewModel.loadDeliveryAddresses() }
    
        CartContent()
    }

    <br />

  • Optimized (Single LaunchedEffect manages multiple concurrent coroutines):

    @Composable
    fun ShoppingCartScreen(viewModel: CartViewModel) {
        // Optimized: 1 LaunchedEffect node launches concurrent jobs
        LaunchedEffect(Unit) {
            launch { viewModel.loadCart() }
            launch { viewModel.loadPaymentMethods() }
            launch { viewModel.loadDeliveryAddresses() }
        }
    
        CartContent()
    }

    <br />

9. Effect execution ordering and teardown costs

Understanding the execution lifecycle and performance costs of Compose effects is critical when choosing between them:

A. Execution order when composition changes are applied

When composition changes are applied (RememberObserver.onRemembered), Compose triggers effects in the following order:

  1. DisposableEffect: Executes synchronously first as composition changes are applied, in the order declared in the composable.

  2. SideEffect : Executes synchronously second, after DisposableEffects have run, before layout and drawing occur.

  3. LaunchedEffect : Launches its coroutine on the composition's CoroutineContext when composition changes are applied. Because it is dispatched asynchronously on that coroutine dispatcher, it does not run synchronously during the apply pass, and it is not guaranteed to run after Layout and Draw.

Warning: Do not assume LaunchedEffect waits until after Layout and Draw to execute. If your code needs layout bounds or coordinates, observe them through layout modifiers (onPlaced, onSizeChanged, or onLayoutRectChanged) rather than relying on effect dispatch timing.

B. Effect allocation and teardown costs

Effects have substantially different overheads:

  • SideEffect: Cheapest effect; executes synchronously on every successful composition pass without lifecycle registration or coroutine allocation.

  • DisposableEffect : Moderate overhead; registers callbacks and runs onDispose synchronously upon key change or exit from composition.

  • LaunchedEffect: Highest overhead; requires allocating a coroutine launcher, launching a new coroutine job on the composition dispatcher, and canceling or tearing down the coroutine job when keys change or the composable exits.

Because canceling a LaunchedEffect incurs coroutine job cancellation and teardown overhead, avoid cycling LaunchedEffect keys frequently during animations or fast scrolling. For synchronous keyed triggers without teardown, always prefer keyed SideEffect(keys) over LaunchedEffect(keys).

3. Side effects API selection guide

Choose the correct Side Effect API based on the execution context and lifecycle requirements:

Use CaseRecommended APIExample
Coroutine tied to Composable lifecycleLaunchedEffect(keys)Triggering network calls or animations when an ID changes
Synchronous cleanup on exitDisposableEffect(keys)Registering and unregistering lifecycle listeners or observers
Launch coroutine from UI callbackrememberCoroutineScope()Triggering a scroll animation on button click or swipe
Convert Compose State into FlowsnapshotFlow { state }Debouncing search queries derived from text field state
Synchronous keyed triggersSideEffect or SideEffect(keys)Updating external imperatively managed views or non-Compose state
Viewport visibility or impression trackingModifier.onVisibilityChangedSending analytics or : logging impressions when an item enters the viewport |

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