Performance: lists and deferred reads
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.
LazyColumnkeys 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 { }ordrawBehind { }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
LazyColumnis 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 read | Phases re-run on change | Typical use |
|---|---|---|
Composable body, or a non-lambda modifier such as Modifier.alpha(a) | Composition, layout, draw | Values that change what is shown |
Modifier.offset { IntOffset(...) }, Modifier.layout { } | Layout, draw | Positions that follow scroll or gestures |
Modifier.graphicsLayer { } | Draw (layer properties) | Alpha, scale, rotation, translation |
Modifier.drawBehind { }, drawWithContent { } | Draw | Colors and custom drawing |
Lazy lists. LazyColumn composes and lays out only the visible items (plus a little prefetch). Two parameters matter most:
keygives each item a stable identity. Without keys, items are identified by position, so after a reorder or an insert at the top, state fromrememberstays with the position, not the item, and the scroll position cannot follow the item the user was looking at. Keys also enableModifier.animateItem(). On Android, keys must be types that can be stored in aBundle(such asInt,LongorString), and they must be unique.contentTypetells 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 { }orModifier.layout { }it invalidates layout; read insidegraphicsLayer { }ordrawBehind { }it invalidates draw only. - Use the lambda form for values that change every frame:
offset { IntOffset(x, y) }instead ofoffset(x.dp, y.dp),graphicsLayer { alpha = a }instead ofalpha(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.firstVisibleItemIndexandfirstVisibleItemScrollOffsetchange constantly while scrolling. Read them in lambda modifiers, or throughderivedStateOfwhen you only need a threshold.- Always pass
keywhen items can be reordered, inserted or removed. Duplicate keys throw at runtime. - Pass
contentTypewhen 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
LazyColumninside a vertically scrollingColumnor anotherLazyColumnwithout a fixed height throws, because it gets an infinite max height. Put everything into one lazy list with severalitemanditemsblocks. ALazyRowinside aLazyColumnis 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
composeCompilerblock (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))
)
}listStateis read only insidescrollProvider(), which is called fromoffset { }andgraphicsLayer { }. Scrolling re-runs layout and draw of the header; neitherFeednorCollapsingHeaderrecomposes.- If
Feedhad passedlistState.firstVisibleItemScrollOffsetas anInt, the read would happen inFeed's body and the whole screen would recompose on every scrolled pixel. key = { it.id }keeps each item's identity across reorders and inserts.Stringkeys areBundle-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
- 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 akey, so items were identified by index.
- Added
key = { it.id }with the task'sLongid. 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.
- 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 toModifier.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 screen now passes
{ listState.firstVisibleItemScrollOffset }to the toolbar, which reads it ingraphicsLayer { 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
keyon lists that change. Remembered item state stays with the position, scroll position cannot follow the item, andanimateItem()cannot work. Pass a unique, stable id. - Using non-
Bundletypes as keys. On Android, lazy list keys must be storable in aBundle. Use the id (Long,String), not the whole data object. - Reading scroll state in the composable body.
listState.firstVisibleItemScrollOffsetread in the body recomposes on every scrolled pixel. Read it inoffset { }orgraphicsLayer { }, or wrap a threshold inderivedStateOf. - 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
LazyColumnin a vertical scroll container. It throws because of the infinite max height. Use oneLazyColumnwith severalitemanditemsblocks. - 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)
- Build the screen. Create a
LazyColumnof 200 rows with a 200 dp header area at the top, and a header box drawn over it. - Do it the slow way first. In the screen composable, compute
val alpha = 1f - (listState.firstVisibleItemScrollOffset / 600f).coerceIn(0f, 1f)and applyModifier.alpha(alpha)to the header. - Measure. Run a release build, open Layout Inspector with recomposition counts, and scroll. Note how fast the screen's count rises.
- Defer the read. Change the header to take
scrollProvider: () -> Intand applyModifier.graphicsLayer { alpha = 1f - (scrollProvider() / 600f).coerceIn(0f, 1f) }. - Add keys. Give every row
key = { it.id }and acontentType, and addModifier.animateItem()to rows. Insert a row at the top with a button. - 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.