DEV Community

Cover image for Why Your Android App Drops Frames: The Jetpack Compose Architecture Guide That Fixes Recomposition Forever
S M Tahosin
S M Tahosin

Posted on

Why Your Android App Drops Frames: The Jetpack Compose Architecture Guide That Fixes Recomposition Forever

For years, Android development carried a reputation for boilerplate and ceremony.

You defined layouts in XML. You manually resolved view IDs with findViewById() or view binding. You synchronized widget states imperatively across Activities and Fragments. And if a single state mutation was missed, your UI fell into an inconsistent state with missing text, mismatched spinners, or phantom clicks.

Then Google delivered Jetpack Compose.

Compose promised to erase that legacy. Inspired by modern declarative paradigms, Compose allows developers to describe user interfaces purely as a function of state:

@Composable
fun UserProfile(user: UserState) {
    Column(modifier = Modifier.padding(16.dp)) {
        Text(text = user.name, style = MaterialTheme.typography.titleLarge)
        Text(text = user.bio, style = MaterialTheme.typography.bodyMedium)
    }
}
Enter fullscreen mode Exit fullscreen mode

State changes, the UI updates automatically. No XML. No view binding. No manual view synchronization.

Developers embraced the transition. Teams rewrote entire feature sets in pure Kotlin. In simple test apps on flagship emulator devices, everything felt fluid and instant.

Then those apps shipped to real-world devices in production.

Users began reporting sluggish scrolling on LazyColumn lists. Frame rates on mid-range Android devices plummeted from a buttery 120Hz down to a stuttering 35Hz. Battery usage surged, and user reviews complained of mysterious battery drain when the app was minimized.

What happened?

The transition to declarative UI traded imperative view hierarchy management for a complex reactive runtime. When developers write Jetpack Compose without understanding its runtime mechanics, they accidentally trigger recomposition cascades, lambda instability, background coroutine leaks, and state loss during process death.

To build responsive, battery-friendly Android applications, you must look beneath the @Composable annotation.

Here is how Jetpack Compose and modern Android architecture actually execute.


1. The Core Engine: The SlotTable and Gap Buffer

A common misconception among web and mobile developers is that Jetpack Compose works like a Virtual DOM.

In React or Vue, changing state produces a tree of virtual nodes in memory. The runtime diffs the old virtual tree against the new virtual tree to calculate physical DOM mutations.

Jetpack Compose does not use a Virtual DOM. It uses a fundamentally different computer science data structure: the SlotTable backed by a Gap Buffer.

The Jetpack Compose SlotTable Gap Buffer Architecture

What Is the SlotTable?

The Jetpack Compose compiler is an official Kotlin compiler plugin. When it encounters a @Composable function, it intercepts the bytecode and rewrites the function signature, injecting a synthetic parameter called the Composer:

// What you write:
@Composable
fun Greeting(name: String)

// What the compiler produces in bytecode:
fun Greeting(name: String, $composer: Composer, $changed: Int)
Enter fullscreen mode Exit fullscreen mode

The $composer parameter gives the function direct access to an internal array called the SlotTable.

The SlotTable is a flat, contiguous array that stores everything your Composable creates, remembers, or depends on. It contains:

  • The positional hierarchy of Composable calls.
  • Every value passed to remember { }.
  • State objects created by mutableStateOf().
  • Parameter values from the previous composition.

The Gap Buffer in Action

To update this flat array without expensive memory reallocations, the SlotTable employs a Gap Buffer, an ancient algorithm famously used in text editors like Emacs:

  1. The array contains a contiguous chunk of unallocated space called the Gap.
  2. When the compiler executes your Composable for the first time, it writes data sequentially into the array until it hits the Gap.
  3. When state changes and a sub-tree of Composables needs to update, the runtime moves the Gap to the current execution index in O(1) amortized time.
  4. New data is written into the Gap, and obsolete elements are overwritten without shifting the entire array.

Positional Memoization

This architecture powers remember.

When you write:

val formattedDate = remember(timestamp) {
    calculateExpensiveFormat(timestamp)
}
Enter fullscreen mode Exit fullscreen mode

There is no dictionary or global hash map looking up timestamp.

Instead, the Composer inspects the current slot index in the SlotTable. It checks whether the stored slot contains the same timestamp value from the previous frame. If the value matches, it returns the cached result in a single array read. If timestamp changed, it re-executes the calculation, overwrites the slot, and stores the new value.

Because lookup is index-based rather than hash-based, positional memoization operates at raw CPU array access speeds.


2. The Stability Trap: Why Your Composables Keep Recomposing

If the SlotTable is so efficient, why do so many Jetpack Compose applications suffer from micro-stutters and dropped frames?

The primary culprit is Unnecessary Recomposition caused by Unstable Parameters.

Compose Compiler Stability Inference and Recomposition Skipping

Skippable vs Restartable

When the Compose compiler processes a @Composable function, it classifies it into two crucial behavioral categories:

  1. Restartable: The Composable can be re-executed when its inputs change or when state it reads mutates. Almost all non-inline Composables are restartable.
  2. Skippable: When a parent Composable recomposes, Compose can completely skip re-executing this child if all of its input parameters are proven to be unchanged.

If a Composable is not skippable, it re-executes every time its parent recomposes, even if its visible data has not changed a single pixel.

How the Compiler Infers Stability

How does the compiler decide if an input parameter is unchanged?

It inspects the type's Stability:

  • Primitive Types (Int, String, Boolean): Inherently Stable. Comparing old == new is trivial.
  • Functional Interfaces / Lambdas: Can be stable if they do not capture unstable local variables.
  • Classes with all val primitive properties: Marked Stable automatically.
  • Mutable Classes (var properties): Marked Unstable. The compiler cannot guarantee that internal properties did not mutate behind its back.

The Collection Trap (List<T> Is Unstable)

Here is the single most common performance trap in modern Android development:

@Composable
fun UserList(users: List<User>) {
    LazyColumn {
        items(users) { user ->
            UserRow(user = user)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

You look at List<User> and assume it is immutable.

The Compose compiler disagrees.

In standard Kotlin, List<T> is an interface. A concrete implementation could easily be a mutable ArrayList<T> passed as a read-only interface reference. Because another thread could mutate the underlying array without changing the list reference, the Compose compiler marks standard Kotlin collections as Unstable.

The result?

Every time UserList receives an update, Compose cannot skip UserRow. If you have 50 items on screen and one item changes, Compose re-evaluates all 50 items from scratch.

The Fix for Unstable Collections

To restore skippability, you have two production solutions:

Solution 1: Kotlinx Immutable Collections

Use official immutable collection types that guarantee structural immutability:

import kotlinx.collections.immutable.ImmutableList

@Composable
fun UserList(users: ImmutableList<User>) {
    // Now 100% skippable!
}
Enter fullscreen mode Exit fullscreen mode

Solution 2: The @Immutable Annotation

Annotate your UI state wrapper classes explicitly:

@Immutable
data class UserUiState(
    val users: List<User> = emptyList()
)
Enter fullscreen mode Exit fullscreen mode

By adding @Immutable, you promise the Compose compiler that references will be treated as immutable, enabling skip optimizations across your entire component tree.


The Lambda Allocation Trap

Consider this button inside a list item:

@Composable
fun UserRow(user: User, onSelect: (String) -> Unit) {
    Button(onClick = { onSelect(user.id) }) {
        Text("View Profile")
    }
}
Enter fullscreen mode Exit fullscreen mode

When UserList recomposes, the lambda { onSelect(user.id) } creates a brand-new object instance in heap memory on every frame.

Because the new lambda instance does not equal the old lambda instance, Button considers its inputs changed and forces a recomposition.

The Fix: Pass stable method references or use remember to stabilize the closure:

// Remembered lambda prevents allocation and maintains reference equality
val onUserClick = remember(user.id) {
    { onSelect(user.id) }
}
Button(onClick = onUserClick)
Enter fullscreen mode Exit fullscreen mode

3. High-Frequency State: Taming derivedStateOf

What happens when your Composable observes a high-frequency state, like a scrolling list offset or a slider?

val listState = rememberLazyListState()

// NAIVE: Recomposes on every single pixel of scroll!
val showScrollToTopButton = listState.firstVisibleItemIndex > 5

if (showScrollToTopButton) {
    ScrollToTopButton(onClick = { ... })
}
Enter fullscreen mode Exit fullscreen mode

As the user scrolls, firstVisibleItemIndex and its underlying scroll offset update 60 to 120 times every second.

Evaluating a boolean condition directly in the Composable body forces the Composable to re-execute on every single pixel change, triggering severe UI jank.

High Frequency State vs derivedStateOf Buffering

The derivedStateOf Buffer

To decouple high-frequency inputs from low-frequency UI updates, Jetpack Compose provides derivedStateOf:

val listState = rememberLazyListState()

// OPTIMIZED: Only triggers recomposition when the boolean result flips
val showScrollToTopButton by remember {
    derivedStateOf { listState.firstVisibleItemIndex > 5 }
}
Enter fullscreen mode Exit fullscreen mode

derivedStateOf observes the high-frequency state internally without notifying the parent Composable. It only notifies the composition when the derived calculation actually changes its output value (e.g., from false to true).

Instead of recomposing 1,000 times during a continuous fling scroll, your Composable recomposes exactly once.


4. The Battery Vampire: Flow Collection and the Lifecycle Trap

Kotlin Coroutines and StateFlow are the modern standard for emitting reactive UI state from Android ViewModels.

However, bridging Kotlin Flows into Jetpack Compose contains one of the most dangerous battery drain pitfalls in the Android ecosystem.

// DANGEROUS: Wastes battery and leaks background work
@Composable
fun DashboardScreen(viewModel: DashboardViewModel) {
    val state by viewModel.uiState.collectAsState()

    DashboardContent(state = state)
}
Enter fullscreen mode Exit fullscreen mode

What is wrong with collectAsState()?

collectAsState() begins collecting the StateFlow when the Composable enters composition and continues collecting until it leaves composition.

Now imagine this scenario:

  1. The user opens your app. DashboardScreen begins collecting viewModel.uiState.
  2. The user presses the Home button. The app goes into the background.
  3. The Activity enters onStop(). The app is no longer visible on screen.

Because DashboardScreen is still in the composition hierarchy, collectAsState() continues collecting in the background.

If your StateFlow is backed by location updates, WebSocket streams, or database observers, your app continues executing background queries, processing JSON payloads, and burning device battery while sitting invisible in the user's pocket.

collectAsState vs collectAsStateWithLifecycle Lifecycle Safety

The Solution: collectAsStateWithLifecycle()

Google introduced the androidx.lifecycle:lifecycle-runtime-compose library specifically to solve this problem:

import androidx.lifecycle.compose.collectAsStateWithLifecycle

@Composable
fun DashboardScreen(viewModel: DashboardViewModel) {
    // SAFE: Automatically pauses collection when app is in the background
    val state by viewModel.uiState.collectAsStateWithLifecycle()

    DashboardContent(state = state)
}
Enter fullscreen mode Exit fullscreen mode

Under the hood, collectAsStateWithLifecycle() wraps collection in repeatOnLifecycle(Lifecycle.State.STARTED):

  • When the Activity transitions to STARTED, collection starts.
  • When the Activity drops to STOPPED (app backgrounded or covered by another app), the collection coroutine is instantly canceled.
  • When the user returns to the app, collection restarts automatically.

Never use raw collectAsState() in UI screens. Always use collectAsStateWithLifecycle().


5. Surviving the OS Assassin: Process Death vs Configuration Changes

One of the most persistent misconceptions among intermediate Android developers revolves around the ViewModel lifecycle:

"My state is stored in a ViewModel, so my user will never lose their data."

This statement is dangerously incomplete.

A ViewModel survives Configuration Changes (such as rotating the phone from portrait to landscape, or resizing a foldable screen). The Android runtime retains the ViewModel instance in memory while destroying and recreating the Activity.

However, a ViewModel does not survive Process Death.

What Is Process Death?

Android operates under aggressive memory constraints. When a user switches from your application to a memory-heavy game or the camera app, the Linux kernel's Low Memory Killer (LMK) needs RAM.

If your app is in the background, Android terminates your entire Linux OS process without warning:

[App in Background] ──► Low RAM Detected ──► Kernel Kills Process (SIGKILL)
Enter fullscreen mode Exit fullscreen mode

When the user returns to your app via the recent apps switcher:

  1. Android starts a brand-new OS process from scratch.
  2. It recreates your Application and Activity classes.
  3. Your ViewModel is completely destroyed and re-instantiated with default values.

If the user was halfway through a multi-step checkout form, their filled fields, selected delivery options, and cart tokens are wiped clean, presenting a jarring blank screen.

The Contract of SavedStateHandle

To survive process death, your ViewModel must preserve critical session identifiers inside SavedStateHandle:

class CheckoutViewModel(
    private val savedStateHandle: SavedStateHandle,
    private val repository: OrderRepository
) : ViewModel() {

    // Survives both configuration changes AND process death
    val orderId: StateFlow<String?> = savedStateHandle.getStateFlow("order_id", null)

    fun setOrder(id: String) {
        savedStateHandle["order_id"] = id
    }
}
Enter fullscreen mode Exit fullscreen mode

SavedStateHandle serializes values into Android's low-level OS Bundle mechanism. When the process is assassinated, the operating system saves that tiny parcel in system server memory. When the process restarts, Android injects the preserved bundle right back into your ViewModel constructor.

The Golden Rule of State Persistence:

  • In-Memory Cache (ViewModel): Transient UI state, complex business objects, loaded list items.
  • SavedStateHandle: Navigation arguments, active IDs, entered text queries, selected tab indices (under 50 KB).
  • Persistent Disk (Room / DataStore): Full offline data, authentication tokens, user preferences.

6. Production Architecture: The Unidirectional Data Flow (UDF) Blueprint

How do the highest-rated Android applications structure state to guarantee predictable rendering, zero recomposition cascades, and total testability?

They implement a strict Unidirectional Data Flow (UDF) with immutable sealed state interfaces.

Here is a production-grade template:

// 1. Immutable State Definition
@Immutable
sealed interface ProductListUiState {
    object Loading : ProductListUiState
    data class Success(val products: ImmutableList<Product>) : ProductListUiState
    data class Error(val message: String) : ProductListUiState
}

// 2. Clear Intent / Event Modeling
sealed interface ProductListIntent {
    data class SelectProduct(val productId: String) : ProductListIntent
    object Refresh : ProductListIntent
}

// 3. Robust ViewModel
@HiltViewModel
class ProductListViewModel @Inject constructor(
    private val repository: ProductRepository,
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val _uiState = MutableStateFlow<ProductListUiState>(ProductListUiState.Loading)
    val uiState: StateFlow<ProductListUiState> = _uiState.asStateFlow()

    fun handleIntent(intent: ProductListIntent) {
        when (intent) {
            is ProductListIntent.Refresh -> loadProducts()
            is ProductListIntent.SelectProduct -> { /* Handle navigation */ }
        }
    }

    private fun loadProducts() {
        viewModelScope.launch {
            _uiState.value = ProductListUiState.Loading
            try {
                val data = repository.getProducts().toPersistentList()
                _uiState.value = ProductListUiState.Success(data)
            } catch (e: Exception) {
                _uiState.value = ProductListUiState.Error(e.localizedMessage ?: "Unknown error")
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Why This Architecture Wins:

  1. Single Source of Truth: State flows down; events flow up. The UI cannot mutate state directly; it can only emit intents.
  2. Deterministic UI Rendering: Using sealed interfaces guarantees that the UI can never accidentally display a loading spinner and an error message simultaneously.
  3. Immutable Collections: Wrapping data in ImmutableList enables the Compose compiler to skip recompositions on unchanged list rows with zero guesswork.

7. Ahead-Of-Time Performance: Baseline Profiles

Have you ever built a Jetpack Compose app, tested it on your physical phone, and felt disappointed by initial startup lag and slight stuttering during the first scroll?

Before panicking, check how you built the app.

In Debug mode, the Android runtime runs in interpreted JIT (Just-In-Time) mode with Compose tracking metadata enabled. Debug builds run up to 4x slower than production release builds.

However, even in Release mode, modern Android apps face an initial warm-up penalty because Android's Android Runtime (ART) must compile DEX bytecode into machine code as users interact with screens.

To eliminate this warm-up lag, Google introduced Baseline Profiles:

[Release APK] + [Baseline Profile Rules] ──► ART Pre-compiles Critical Code at Install Time ──► Instant 60-120Hz Scroll
Enter fullscreen mode Exit fullscreen mode

A Baseline Profile is a text file bundled with your app that tells ART which classes and methods are critical for app startup and list scrolling. When the user downloads your app from Google Play, ART pre-compiles those exact Compose routines into machine code at install time.

Adding a Baseline Profile typically yields:

  • Up to 40% faster app startup times.
  • Immediate zero-jank frame rendering during the user's very first scroll.

The Mental Shift

Building high-performance Android apps in the modern era requires letting go of obsolete mental habits:

  • Stop thinking of UI as a tree of persistent XML views that you manually modify.
  • Jetpack Compose is a compiler-driven reactive engine powered by the SlotTable gap buffer.
  • Unstable parameters and raw List<T> types trigger silent, expensive recomposition storms.
  • collectAsStateWithLifecycle() protects user battery life when screens enter the background.
  • And ViewModels must be backed by SavedStateHandle to survive the operating system's Low Memory Killer.

Once you master these runtime mechanics, declarative Android development transforms from a mysterious, lag-prone struggle into one of the most expressive, resilient, and blazingly fast engineering platforms in software.

How has your team tackled recomposition optimization in Jetpack Compose? Have you run into stability surprises with Kotlin collections, or integrated Baseline Profiles into your release pipeline? Share your production experiences and architecture strategies in the comments below.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The List instability trap is the part that would have caught me — I had always treated a read-only List as stable, and the ArrayList-underneath explanation makes it obvious why the compiler can't promise that. The collectAsStateWithLifecycle point lands too: a StateFlow backed by location updates keeps collecting after onStop, which is exactly the kind of silent battery drain I would never notice in testing. Good breakdown of the SlotTable mechanics as well.