Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 104 ยท Quality, Performance and Security

Performance and Profiling

Find and fix Android jank, startup and memory problems with Layout Inspector, Perfetto and the profiler, then speed up releases with R8, baseline profiles and macrobenchmarks.

Users rarely say "your app has a slow render pipeline". They say it "feels laggy", "takes forever to open" or "drains my battery". Performance is the gap between what your code does and what a person on a three-year-old, mid-range phone perceives. Because you develop on a fast machine and a fresh emulator, you will not notice most problems unless you measure them.

This lesson gives you a method and a toolbox. You will learn what jank is and why a frame has a time budget, how to find slow code with the Layout Inspector, the profiler and Perfetto, what makes startup slow, how baseline profiles, macrobenchmarks and R8 speed up release builds, and how memory leaks happen. It follows Instrumented, Room and Navigation Tests and builds on Recomposition and Stability. The profiling tools need a device and the Android SDK, so the real tooling and Gradle code are read-only. The TryIt blocks are plain-Kotlin stand-ins: a frame-budget simulator and a reachability model for leaks. They teach the arithmetic and the logic, not real measurements.

The golden rule: measure first

Intuition about performance is wrong surprisingly often. The loop is always the same:

  1. Reproduce the slowness on a release-like build (a debug build is much slower and misleads you).
  2. Measure it with a tool and write the number down.
  3. Change one thing.
  4. Measure again and keep the change only if the number improved.

Profile on a real, modest device, with debuggable false and R8 enabled, because debug builds skip optimizations and emulators run on your desktop CPU.

Jank and the frame budget

The screen refreshes at a fixed rate, usually 60 Hz, and many phones now run at 90 or 120 Hz. At 60 Hz the system wants a new frame every 1000 / 60, about 16.7 ms. At 120 Hz the budget is only 8.3 ms. In that time your app must handle input, run animations, compose and measure the UI, and record drawing commands; then the GPU renders them.

If the work for a frame takes longer than the budget, the screen shows the previous frame again. The user sees a stutter, called jank. A frame that takes 40 ms is not "a bit slow": it caused two missed refreshes.

flowchart LR
    A["Input<br/>events"] --> B["Animation<br/>and state"]
    B --> C["Compose, layout<br/>and draw (UI thread)"]
    C --> D["Render and<br/>display (GPU)"]
    D --> E{"Within 16.7 ms?"}
    E -- "yes" --> F["Smooth"]
    E -- "no" --> G["Jank: frame repeated"]

Each frame passes through the UI thread and the GPU; missing the deadline repeats the old frame.

Almost all jank comes from doing too much on the main thread: reading a file, parsing JSON, a long loop, a heavy synchronous database call, or a composable that recomposes thousands of times. The fix is usually to move the work to a background dispatcher (see Coroutines on Android) or to avoid doing it at all.

A frame-budget simulator

This stand-in takes a list of frame costs in milliseconds and a refresh rate. It computes the budget, counts how many refreshes each frame missed, and reports the share of janky frames. Real tools such as the profiler and JankStats report the same kind of numbers, measured from a running app.

Kotlin Frame budget and jank counter (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The 42 ms frame costs three refreshes at 60 Hz, two of them missed. At 120 Hz the same code misses frames more often, because several 9 to 12 ms frames now exceed the 8.3 ms budget. High-refresh screens make sloppy code visible.

Finding the problem: the tools

Android Studio and the platform give you a layered set of tools. Start with the cheapest.

  • Layout Inspector shows the live UI tree. For Compose it adds recomposition counts and skip counts for every composable, which is the quickest way to find a composable that recomposes on every frame (see Recomposition and Stability).
  • Compose compiler reports list which composables and types the compiler considers skippable and stable. They explain why something recomposes.
  • CPU profiler (the Studio profiler) records method traces or system traces and shows which functions use the main thread's time.
  • Perfetto is the system-wide tracing tool. A trace shows every thread, the frame timeline, CPU scheduling, binder calls and your own custom trace sections. You open the trace file in the Perfetto web UI and zoom into the slow frame.
  • Memory profiler and heap dumps show allocations and what objects stay alive.
  • JankStats (a library) reports janky frames from real users, with the app state at the time.

You can add your own named sections to a trace, which makes your code visible in Perfetto:

Kotlin
// read-only example: custom trace section (needs androidx.tracing)
import androidx.tracing.trace

fun loadFeed(): List<Post> = trace("loadFeed") {
    val raw = readFromDisk()
    parse(raw)
}

When you read a trace, look for long slices on the main thread (named main or your package), then walk down to the callee that dominates. Fix the biggest slice first; small slices are not worth your time.

Startup time

Startup comes in three flavors, and users feel the first one most.

Start type What happens Typical cost
Cold The process does not exist: the system forks it, creates Application, the first activity and draws the first frame Slowest
Warm The process lives but the activity was destroyed and is recreated Medium
Hot The activity is simply brought back to the foreground Fastest

Cold start is what to optimize. Common causes of a slow one:

  • Heavy work in Application.onCreate: initializing ten SDKs, reading preferences, building dependency graphs eagerly. Defer what the first screen does not need, or use the App Startup library to control initialization order.
  • Blocking the first frame with disk or network reads. Show something immediately and load the rest asynchronously.
  • A huge first screen with many composables or images.
  • Class loading and interpretation. The runtime has to load and, at first, interpret code that has not been compiled ahead of time. Baseline profiles fix this (next section).

Android reports the time to the first frame as "Displayed" in Logcat (see Running, Debugging and Logcat). A call to reportFullyDrawn() tells the system when content is really ready, so Android vitals measure the right moment.

Baseline profiles

Android's runtime compiles code in several ways. A freshly installed app starts mostly interpreted and gets compiled as it runs, which means the first launches are slow. A baseline profile is a list of classes and methods that matter at startup and during key interactions, shipped inside your app. At install time the system compiles exactly those methods ahead of time, so even the first launch runs compiled code. Typical results are noticeably faster startup and less jank in the first scrolls, without changing your code.

You generate a profile by writing a test that exercises critical user journeys on a device. The Baseline Profile Gradle plugin turns the recorded methods into a text file bundled with the release build:

Kotlin
// read-only example: baselineprofile module (needs Macrobenchmark)
@RunWith(AndroidJUnit4::class)
class BaselineProfileGenerator {

    @get:Rule
    val rule = BaselineProfileRule()

    @Test
    fun generate() = rule.collect(packageName = "com.example.shop") {
        pressHome()
        startActivityAndWait()
        // Scroll the main list: these methods land in the profile
        device.findObject(By.res("feed")).fling(Direction.DOWN)
        device.waitForIdle()
    }
}

Libraries such as Compose and AndroidX ship their own profiles, so your app already benefits from some. Your own profile covers your startup path.

Macrobenchmark

A macrobenchmark measures your whole app from the outside: it starts the process, drives the UI and records startup time and frame timing across many iterations on a real device. Unlike a microbenchmark of one function, it answers "did this change make the app start faster for users?". Because results vary, it runs several iterations and reports the median and spread.

Kotlin
// read-only example: macrobenchmark module
@RunWith(AndroidJUnit4::class)
class StartupBenchmark {

    @get:Rule
    val rule = MacrobenchmarkRule()

    @Test
    fun coldStartWithProfile() = rule.measureRepeated(
        packageName = "com.example.shop",
        metrics = listOf(StartupTimingMetric()),
        compilationMode = CompilationMode.Partial(),
        startupMode = StartupMode.COLD,
        iterations = 10,
    ) {
        pressHome()
        startActivityAndWait()
    }
}

Run the same test with CompilationMode.None() and with the profile applied, and compare the medians: that is how you prove a baseline profile is worth keeping. Add FrameTimingMetric() to measure scrolling smoothness.

R8: shrinking, optimizing, obfuscating

R8 is the tool that processes your code in release builds. It does three jobs:

  • Shrinks: removes classes, methods and resources that nothing uses. This makes the app smaller and faster to install.
  • Optimizes: inlines methods, removes dead branches and merges classes.
  • Obfuscates: renames classes and members to short names, which shrinks code further and makes reverse engineering a little harder.

You switch it on in the release build type:

Kotlin
// read-only example: app/build.gradle.kts
android {
    buildTypes {
        release {
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
}

R8 decides what is unused by analyzing calls it can see. Code that is reached only through reflection or by name from outside (some serialization libraries, JNI, classes named in XML) looks unused, so R8 removes or renames it and the app crashes only in release. The cure is a keep rule in proguard-rules.pro:

TEXT
# read-only example: proguard-rules.pro
-keep class com.example.shop.network.dto.** { *; }

Most modern libraries ship their own consumer rules, so you need few of your own. Always test the release build, and keep the mapping.txt file that R8 generates: it translates obfuscated stack traces back to your real names (see Signing and Release Builds).

Memory leaks

A memory leak is an object that your app no longer needs but that is still reachable, so the garbage collector cannot free it. On Android the typical victim is an Activity or a View, because they hold the whole UI tree and its bitmaps. Rotate the screen ten times with a leak and you hold ten dead activities.

flowchart LR
    A["Static or singleton<br/>(lives as long as the process)"] --> B["Reference to<br/>destroyed Activity"]
    B --> C["View tree and bitmaps<br/>cannot be collected"]

Anything reachable from a GC root, such as a static field, stays alive.

Common causes:

  • A singleton or companion object that stores a Context, an activity or a view.
  • A listener or callback registered with a long-lived object and never unregistered.
  • A coroutine or Handler that outlives the screen and captures it. Use viewModelScope or a lifecycle-aware scope.
  • An inner class or lambda that implicitly captures the enclosing activity.
  • A ViewModel holding a Context or view reference (see ViewModel).

In debug builds, the LeakCanary library watches destroyed activities and fragments and shows a notification with the reference path when one stays in memory. The Studio memory profiler can also capture a heap dump so you can search for instances of your activity class after leaving the screen.

A leak, modeled as reachability

The stand-in below models a tiny object graph. A garbage collector keeps whatever is reachable from the roots, and a static holder is a root. We destroy an "activity" and ask whether it can be collected. This mirrors the reasoning behind LeakCanary: after onDestroy, nothing but the system should still point to the activity.

Kotlin Why a destroyed activity cannot be collected (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In case 2 the cache sits on a path from the root to the activity, so all its views stay alive. In case 3 the singleton holds only the application context, which lives as long as the process anyway, so nothing leaks. In real code, the rule of thumb is: anything that outlives a screen may hold applicationContext, never an activity.

ANRs and StrictMode

Jank is the app being slow; an ANR ("Application Not Responding") is the app being stuck long enough that the system shows the user a dialog offering to close it. ANRs also count against you in Android vitals on Google Play, and a bad ANR rate lowers your app's visibility in the store.

What triggers an ANR

The system starts a timer when it hands work to your main thread and raises an ANR if the work does not finish in time. The common limits are:

Situation Typical timeout
Input event (touch, key) not handled 5 seconds
Foreground BroadcastReceiver.onReceive() not finished 10 seconds
Background receiver 60 seconds
Service lifecycle callbacks (onCreate, onStartCommand) About 20 seconds (foreground) or 200 seconds (background)
Foreground service that never calls startForeground() About 10 seconds

The exact numbers vary between Android versions and device makers, so treat them as orders of magnitude. The cause is almost always the same: the main thread was busy or blocked. Typical culprits are disk or network calls on the main thread, a synchronous database query, a lock held by a background thread that the main thread then waits for (a deadlock or contention), or a receiver that does real work instead of handing it off to WorkManager or a coroutine, see Broadcast Receivers.

Reading an ANR

When an ANR happens, the system writes the stack of every thread to /data/anr/ (you will see it on a device you control) and Google Play collects traces from real users in Android vitals. Open the trace and look at the main thread first:

  • If it is in Object.wait, futex or a synchronized block, it is waiting for a lock; find which thread holds it.
  • If it is inside read, SQLiteConnection.nativeExecute or an HTTP call, you are doing I/O on the main thread.
  • If it is in your own code running a loop, you are doing CPU work in the wrong place.
  • If the main thread looks idle, the system itself was overloaded, or a different process was slow (a binder call to another app can block you).

StrictMode: catching it in development

StrictMode is a developer tool that watches the thread it is enabled on and reports the mistakes that later turn into ANRs. Turn it on in debug builds only, early in Application.onCreate():

Kotlin
// read-only example: needs Android
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        if (BuildConfig.DEBUG) {
            StrictMode.setThreadPolicy(
                StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()
                    .detectCustomSlowCalls()
                    .penaltyLog()            // write a stack trace to Logcat
                    .build()
            )
            StrictMode.setVmPolicy(
                StrictMode.VmPolicy.Builder()
                    .detectLeakedClosableObjects()
                    .detectLeakedSqlLiteObjects()
                    .detectActivityLeaks()
                    .penaltyLog()
                    .build()
            )
        }
    }
}

The thread policy flags slow operations on the thread it is set on (disk and network on the main thread). The VM policy flags process-wide mistakes such as unclosed cursors and streams or leaked activities. penaltyLog() is gentle. penaltyDeath() crashes the app on a violation, which is useful in CI or tests because nobody can ignore it, and penaltyFlashScreen() flashes the screen red. Filter Logcat by the tag StrictMode to see the stack traces. For actual leak hunting, use the tools from Memory leaks, LeakCanary in particular; StrictMode only catches some leak patterns.

The stand-in below models the idea with a fake main thread. A watchdog times each task on it, and a "strict" wrapper reports any call tagged as disk or network I/O, while a timeout check plays the role of the ANR timer. Real StrictMode hooks the framework's own I/O paths instead of tags, and real ANR detection lives in the system server.

Kotlin A tiny StrictMode and ANR watchdog (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The fix is the same as in every other section of this lesson: keep the main thread for UI work, move I/O and heavy computation to Dispatchers.IO or Default (see Coroutines on Android), and never wait on a lock or a slow binder call there.

Smooth RecyclerView scrolling

Lists are where most users feel jank. These habits fix the usual causes (see RecyclerView for the basics):

  • Keep onBindViewHolder cheap. It runs on the main thread for every row that scrolls in. No disk, no network, no JSON parsing, no creating adapters or listeners per bind. Precompute display strings in the ViewModel.
  • Use ListAdapter with DiffUtil instead of notifyDataSetChanged(). Targeted calls such as notifyItemChanged(position) or notifyItemInserted keep unaffected rows untouched and let ItemAnimator work.
  • Give rows stable IDs (setHasStableIds(true) plus getItemId) when items can reorder, so the view can reuse holders and animate moves.
  • Flatten the row layout. A ConstraintLayout with few nested containers measures faster than deep LinearLayout trees. Avoid layout_weight chains inside rows.
  • Do not nest scrolling layouts of the same direction. A RecyclerView inside a NestedScrollView is measured at full height and loses recycling. If you need rows inside rows, use a horizontal inner list with a shared RecycledViewPool and a fixed size (setHasFixedSize(true) when the list's size does not depend on its content).
  • Load images asynchronously and at the right size. Coil, Glide or Picasso decode off the main thread, cache, and downsample to the view size; request thumbnails for list rows (Image loading).
  • Prefetch and cache tuning. LinearLayoutManager prefetches the next rows by default; raise setItemViewCacheSize only if you measured a benefit, because it costs memory.
  • Measure, do not guess. Use the Profile GPU rendering bars or a FrameTimingMetric macrobenchmark while scrolling, as in the sections above.

In Compose the same rules appear as: provide a stable key for items, hoist expensive work out of item composables, use remember for derived values and avoid reading fast-changing state in a parent composable (Lazy lists and grids, Recomposition).

Quick wins checklist

  • Never block the main thread: move I/O and CPU work to Dispatchers.IO or Default.
  • In lists, give items stable keys and avoid heavy work inside item composables (see Lazy Lists and Grids).
  • Use derivedStateOf for values computed from fast-changing state (see rememberSaveable, derivedStateOf and Collections).
  • Load images at the size you display them, and let a library cache them.
  • Enable R8, ship a baseline profile and verify both with a macrobenchmark.
  • Keep Application.onCreate nearly empty.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. At 60 Hz, about how long does your app have to produce one frame without causing jank?

    1000 ms divided by 60 frames is about 16.7 ms. At 120 Hz the budget halves to about 8.3 ms.
  2. 2. Why should you profile a release-like build on a real device instead of a debug build on your emulator?

    Debug builds are slower and unoptimized, and emulators do not match real hardware, so measurements from them do not describe what users experience.
  3. 3. What does a baseline profile do?

    A baseline profile tells the runtime which classes and methods to precompile, so the first launches do not run mostly interpreted code. Shrinking and renaming are R8's work.
  4. 4. A release build crashes with ClassNotFoundException for a class that is only used through reflection. What is the most likely cause and fix?

    R8 only sees direct references. Classes reached via reflection look unused and are removed or renamed, so you protect them with -keep rules.
  5. 5. Which object is safe to store in a singleton that outlives all screens?

    The application context lives as long as the process, so holding it cannot keep a destroyed screen alive. Activities and views would be leaked.

Summary

  • Performance work is a loop of reproduce, measure, change one thing, measure again, on a release-like build and a real device.
  • A frame has a budget of about 16.7 ms at 60 Hz and 8.3 ms at 120 Hz; missing it repeats the old frame and the user sees jank. Most jank is main-thread work.
  • Layout Inspector (with recomposition counts), the profiler, Perfetto, heap dumps and JankStats each answer different questions; start with the cheapest.
  • Cold start is the one to optimize: keep Application.onCreate light and never block the first frame.
  • Baseline profiles precompile critical code paths; macrobenchmarks prove the effect on startup and scrolling.
  • R8 shrinks, optimizes and obfuscates release builds; reflection-only code needs keep rules, and you keep mapping.txt to decode traces.
  • An ANR means the main thread was stuck (input after about 5 s, receivers about 10 s); read the main thread's stack in the trace, and enable StrictMode in debug builds to catch disk and network calls on it early.
  • Leaks are objects that stay reachable from a GC root; never let something long-lived hold an activity, and use LeakCanary in debug builds.
  • Profiling tools and Gradle code are read-only here; the TryIts are stand-ins for the frame arithmetic and for reachability.

Next: Securing Your App