Performance: lists and deferred reads

Learn Jetpack Compose list performance on Android: LazyColumn keys and contentType, Compose phases, and deferred state reads with offset and graphicsLayer. About 25 minutes.

Why it matters

  • Lists are where Compose performance problems show up first: scrolling runs layout and draw every frame, and anything that recomposes per frame causes jank.
  • LazyColumn keys decide whether remembered item state, scroll position and item animations follow the right item when data changes.
  • Reading fast-changing state such as a scroll offset in a composable body recomposes the screen on every frame. Moving that read into offset { }, graphicsLayer { } or drawBehind { } skips composition.
  • Senior Android interviews ask about the composition, layout and draw phases and how you would diagnose a janky LazyColumn.

The simple explanation

  • A Compose frame is a three-step print shop: decide what goes on the page (composition), arrange it (layout), then ink it (draw).
  • If a change only affects the ink colour, you only re-ink. If it changes where things sit, you re-arrange and re-ink. Only a change in what is on the page needs all three.
  • A deferred read tells Compose which step a value belongs to, so a change re-runs only that step and the ones after it.
  • A LazyColumn is a conveyor belt that only builds the plates in front of you; the key is the name tag that keeps each plate's extras with the right plate when the order changes.

What is a deferred read in Jetpack Compose? It is reading a State inside a lambda that Compose calls in a later phase instead of in the composable body. Compose tracks state reads per phase: a read during composition invalidates composition, a read inside Modifier.offset { } or Modifier.layout { } invalidates only layout, and a read inside Modifier.graphicsLayer { }, drawBehind { } or drawWithContent { } invalidates only drawing.

Where the state is readPhases re-run on changeTypical use
Composable body, or a non-lambda modifier such as Modifier.alpha(a)Composition, layout, drawValues that change what is shown
Modifier.offset { IntOffset(...) }, Modifier.layout { }Layout, drawPositions that follow scroll or gestures
Modifier.graphicsLayer { }Draw (layer properties)Alpha, scale, rotation, translation
Modifier.drawBehind { }, drawWithContent { }DrawColors and custom drawing

Lazy lists. LazyColumn composes and lays out only the visible items (plus a little prefetch). Two parameters matter most:

  • key gives each item a stable identity. Without keys, items are identified by position, so after a reorder or an insert at the top, state from remember stays with the position, not the item, and the scroll position cannot follow the item the user was looking at. Keys also enable Modifier.animateItem(). On Android, keys must be types that can be stored in a Bundle (such as Int, Long or String), and they must be unique.
  • contentType tells Compose which items have the same structure. Compositions are reused only between items of the same content type, so a list mixing headers, ads and rows reuses compositions more efficiently when each kind has its own type.

Notes

  • State read in a composable body invalidates composition; read inside offset { } or Modifier.layout { } it invalidates layout; read inside graphicsLayer { } or drawBehind { } it invalidates draw only.
  • Use the lambda form for values that change every frame: offset { IntOffset(x, y) } instead of offset(x.dp, y.dp), graphicsLayer { alpha = a } instead of alpha(a).
  • Pass state down as a lambda (scrollProvider: () -> Int) instead of a value, so the read happens in the child's lambda modifier rather than in the parent.
  • LazyListState.firstVisibleItemIndex and firstVisibleItemScrollOffset change constantly while scrolling. Read them in lambda modifiers, or through derivedStateOf when you only need a threshold.
  • Always pass key when items can be reordered, inserted or removed. Duplicate keys throw at runtime.
  • Pass contentType when a list mixes different kinds of item.
  • Do not give items a size of 0 px before their content loads (for example, an image with no placeholder). The list may compose many items at once to fill the viewport; give placeholders their expected size.
  • A LazyColumn inside a vertically scrolling Column or another LazyColumn without a fixed height throws, because it gets an infinite max height. Put everything into one lazy list with several item and items blocks. A LazyRow inside a LazyColumn is fine.
  • Measure performance in a release build with R8 and a Baseline Profile. Debug builds of Compose are much slower and mislead you.
  • To check stability of item parameters, use the compiler reports from the composeCompiler block (reportsDestination).

Code example

A list with a header image that fades and moves as you scroll. The scroll offset is read only in lambda modifiers, and items use key and contentType.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
 
sealed interface FeedItem {
    val id: String
    data class Section(override val id: String, val title: String) : FeedItem
    data class Post(override val id: String, val text: String) : FeedItem
}
 
@Composable
fun Feed(items: List<FeedItem>) {
    val listState = rememberLazyListState()
 
    // Lambda: the child reads the value later, in its own phase
    val headerScroll = {
        if (listState.firstVisibleItemIndex == 0) listState.firstVisibleItemScrollOffset else Int.MAX_VALUE
    }
 
    Box(Modifier.fillMaxSize()) {
        LazyColumn(state = listState) {
            item(key = "header-space", contentType = "header") {
                Box(Modifier.height(200.dp))
            }
            items(
                items = items,
                key = { it.id },
                contentType = { it::class },
            ) { item ->
                when (item) {
                    is FeedItem.Section -> Text(item.title, Modifier.padding(16.dp))
                    is FeedItem.Post -> Text(item.text, Modifier.padding(horizontal = 16.dp, vertical = 8.dp))
                }
            }
        }
        CollapsingHeader(scrollProvider = headerScroll)
    }
}
 
@Composable
fun CollapsingHeader(scrollProvider: () -> Int) {
    Box(
        Modifier
            .fillMaxWidth()
            .height(200.dp)
            .offset { IntOffset(0, -(scrollProvider().coerceAtMost(200.dp.roundToPx()) / 2)) } // layout
            .graphicsLayer { alpha = 1f - (scrollProvider() / 200.dp.toPx()).coerceIn(0f, 1f) } // draw
            .background(Color(0xFF3F51B5))
    )
}
  • listState is read only inside scrollProvider(), which is called from offset { } and graphicsLayer { }. Scrolling re-runs layout and draw of the header; neither Feed nor CollapsingHeader recomposes.
  • If Feed had passed listState.firstVisibleItemScrollOffset as an Int, the read would happen in Feed's body and the whole screen would recompose on every scrolled pixel.
  • key = { it.id } keeps each item's identity across reorders and inserts. String keys are Bundle-compatible, which Android requires.
  • contentType = { it::class } keeps section and post compositions in separate reuse pools.

Run the idea in plain Kotlin

A model of how many times each phase runs when a scroll offset changes ten times, depending on where the value is read.

enum class Phase { COMPOSITION, LAYOUT, DRAW }

class Counters {
  var composition = 0
  var layout = 0
  var draw = 0

  // A change re-runs the phase that read it and every phase after it
  fun invalidate(readIn: Phase) {
      if (readIn == Phase.COMPOSITION) composition++
      if (readIn <= Phase.LAYOUT) layout++
      draw++
  }
}

fun simulate(readIn: Phase, scrollChanges: Int): Counters {
  val c = Counters()
  c.composition = 1; c.layout = 1; c.draw = 1 // first frame
  repeat(scrollChanges) { c.invalidate(readIn) }
  return c
}

fun main() {
  val cases = listOf(
      "read in composable body" to Phase.COMPOSITION,
      "read in offset { }" to Phase.LAYOUT,
      "read in graphicsLayer { }" to Phase.DRAW,
  )
  for ((label, phase) in cases) {
      val c = simulate(phase, scrollChanges = 10)
      println(label + ": composition=" + c.composition + ", layout=" + c.layout + ", draw=" + c.draw)
  }
}

Expected output:

read in composable body: composition=11, layout=11, draw=11
read in offset { }: composition=1, layout=11, draw=11
read in graphicsLayer { }: composition=1, layout=1, draw=11

In production

Checkbox state jumped to another row after a new item arrived
  • A to-do list kept an "expanded" flag per row with remember { mutableStateOf(false) } inside the item.
  • When a new task was inserted at the top, the expanded state stayed at the same position, so a different task appeared expanded. The list also jumped instead of keeping the user's place.
  • The list used items(tasks) { ... } without a key, so items were identified by index.
The fix
  • Added key = { it.id } with the task's Long id. Remembered state now follows the task, and the list keeps the visible item in place when items are inserted above it.
  • The expanded flag moved into the UI state from the ViewModel, so it also survives process death and configuration changes.
  • With keys in place the team added Modifier.animateItem() to animate inserts and moves.
Whole screen recomposed while scrolling
  • A profile screen faded its toolbar title based on scroll. The screen computed val titleAlpha = (listState.firstVisibleItemScrollOffset / 300f).coerceIn(0f, 1f) in its body and passed it to Modifier.alpha(titleAlpha).
  • Layout Inspector showed the screen composable's recomposition count rising on every scroll frame, and a Macrobenchmark frame timing test on a mid-range device showed many slow frames.
The fix
  • The screen now passes { listState.firstVisibleItemScrollOffset } to the toolbar, which reads it in graphicsLayer { alpha = ... }.
  • A "show divider" flag that only flips at the top of the list was moved to derivedStateOf { listState.firstVisibleItemIndex > 0 }.
  • The screen's recomposition count stopped changing during scroll, and the team kept the Macrobenchmark scroll test in CI to catch regressions.

Common mistakes

  • No key on lists that change. Remembered item state stays with the position, scroll position cannot follow the item, and animateItem() cannot work. Pass a unique, stable id.
  • Using non-Bundle types as keys. On Android, lazy list keys must be storable in a Bundle. Use the id (Long, String), not the whole data object.
  • Reading scroll state in the composable body. listState.firstVisibleItemScrollOffset read in the body recomposes on every scrolled pixel. Read it in offset { } or graphicsLayer { }, or wrap a threshold in derivedStateOf.
  • Passing fast-changing values down as parameters. The read then happens in the parent. Pass a lambda (() -> Int) and read it in the child's lambda modifier.
  • Nesting a LazyColumn in a vertical scroll container. It throws because of the infinite max height. Use one LazyColumn with several item and items blocks.
  • Zero-sized placeholders. Items that are 0 px tall before images load make the list compose far more items than needed. Give placeholders a fixed size.
  • Judging performance from a debug build. Compose in debug is much slower. Measure release builds with a Baseline Profile.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is a deferred read, and why does offset { } help performance?”

“What do key and contentType do in a LazyColumn?”

“When would you use derivedStateOf in a list screen?”

“How do you diagnose a janky LazyColumn?”

Quiz

A header's alpha is set with Modifier.graphicsLayer { alpha = 1f - scrollProvider() / 300f }. What re-runs while scrolling?

A list without keys inserts a new item at the top. What goes wrong?

What does contentType change in a LazyColumn?

You put a LazyColumn inside a Column with Modifier.verticalScroll. What happens?

0 of 4 answered

Mini task

Make a scrolling header cheap (25 min)

  1. Build the screen. Create a LazyColumn of 200 rows with a 200 dp header area at the top, and a header box drawn over it.
  2. Do it the slow way first. In the screen composable, compute val alpha = 1f - (listState.firstVisibleItemScrollOffset / 600f).coerceIn(0f, 1f) and apply Modifier.alpha(alpha) to the header.
  3. Measure. Run a release build, open Layout Inspector with recomposition counts, and scroll. Note how fast the screen's count rises.
  4. Defer the read. Change the header to take scrollProvider: () -> Int and apply Modifier.graphicsLayer { alpha = 1f - (scrollProvider() / 600f).coerceIn(0f, 1f) }.
  5. Add keys. Give every row key = { it.id } and a contentType, and add Modifier.animateItem() to rows. Insert a row at the top with a button.
  6. Measure again.

Done condition: while scrolling, the screen and header recomposition counts no longer change, the header still fades, and inserting a row at the top animates without moving the rows you were looking at.

Next: Memory leaks and LeakCanary