Jank, frames and Perfetto

Learn Android jank: frame budgets at 60 and 120 Hz, the rendering pipeline, JankStats, and finding dropped frames with Perfetto system traces. About 25 minutes.

Why it matters

  • Jank (stutter from dropped or late frames) is one of the most visible performance problems. At 60 Hz each frame has about 16.7 ms; at 120 Hz only about 8.3 ms, so code that was fine on older screens can stutter on newer ones.
  • Perfetto system traces are the standard way to see why a frame was late: which thread was busy, whether the main thread was blocked, and whether the app or the system missed the deadline. Senior interviews often ask you to walk through one.
  • The JankStats library reports janky frames from real users in production, tagged with UI state, so you know which screen and action stutters.
  • Frame-budget work connects to the rest of this module: slow startup delays the first frame, main-thread I/O causes both jank and ANRs, and allocation churn from leaks or big objects adds GC work during scrolling.

The simple explanation

  • A kitchen sends out one plate every 16.7 ms (the frame budget at 60 Hz).
  • Each station (input, animation, layout, draw, render, GPU, composite) must finish its part before the plate goes out.
  • If one station is slow, the plate misses its slot and the customer sees the previous plate again: that is a dropped frame, a stutter.
  • Perfetto is the kitchen camera that records every station's timing.
  • JankStats is the shift report from real customers: which plates were late and what was being served.
  • At 120 Hz the slot shrinks to 8.3 ms, so the same slow station causes more misses.

What is jank in Android, and how do you find it? Jank is when the app does not produce a new frame in time for the display's next refresh, so the previous frame stays on screen and motion stutters. You find it by measuring (JankStats in production, Macrobenchmark's FrameTimingMetric in tests) and then explaining it with a Perfetto system trace, which shows exactly what each thread was doing during the late frame.

The display refreshes at a fixed rate (60 Hz = 16.7 ms, 90 Hz = 11.1 ms, 120 Hz = 8.3 ms per frame). The vsync signal makes Choreographer start a frame on the main thread. Each frame passes through these stages:

StageWhere it runsWhat happens
InputMain threadTouch and key events dispatched to Views or Compose pointer input
AnimationMain threadAnimators and Compose animations advance to the frame time
Measure and layoutMain threadView measure() and layout(), or Compose composition and layout
Draw (record)Main threadViews and Compose record drawing commands into display lists
Sync and renderRenderThreadDisplay lists turned into GPU commands; the buffer is queued
GPUGPUExecutes the drawing commands
CompositeSurfaceFlingerCombines app and system layers for the display

If the work is not ready by its deadline, the frame is dropped or shown late. Most app-side jank comes from long main-thread work (heavy onBindViewHolder, deep layouts, unnecessary recomposition, main-thread I/O), long RenderThread or GPU work (large bitmaps, overdraw, complex shaders), or the main thread waiting on a lock.

Tools:

  • Perfetto records a system trace. Use Android Studio's profiler (the system trace / "Capture System Activities" option), the on-device System Tracing app, or adb shell perfetto. Open the trace in ui.perfetto.dev or Android Studio. On Android 12+ the Expected Timeline and Actual Timeline tracks of your process show each frame's deadline and a jank type such as "App Deadline Missed" or "Buffer Stuffing".
  • Custom trace sections: wrap code in trace("Feed:bind") { ... } from androidx.tracing so it appears as a named slice on its thread in the trace.
  • JankStats (androidx.metrics:metrics-performance) calls your listener for each frame with FrameData (isJank, frameDurationUiNanos, states). It uses FrameMetrics on Android 7 (API 24)+ and falls back to OnPreDrawListener on older versions.
  • Macrobenchmark FrameTimingMetric measures frame times for a scripted scroll or animation in tests, so regressions show before release.

Notes

  • Frame budget is 1000 ms divided by the refresh rate: about 16.7 ms at 60 Hz, 11.1 ms at 90 Hz and 8.3 ms at 120 Hz. Read the real rate from the Display instead of hardcoding 60 Hz.
  • A missed frame shows the previous frame again for another refresh. Users notice repeated misses during scrolling and animations most.
  • Capture a trace from the command line with adb shell perfetto -o /data/misc/perfetto-traces/trace.perfetto-trace -t 10s sched freq gfx view input, then adb pull the file and open it in ui.perfetto.dev.
  • In Perfetto, find the frame on the main thread (Choreographer#doFrame slices) and on the RenderThread (DrawFrame slices). Check whether the main thread was Running or Sleeping/Blocked during the long frame; blocked time points to locks, I/O or binder calls.
  • On Android 12+, the Actual Timeline track colours late frames and gives a jank type. "App Deadline Missed" means your app's work was late; SurfaceFlinger or display jank types point at the system side.
  • Add custom slices with androidx.tracing trace("name") { }. When tracing is not active the calls are cheap, so they can stay in release code. Keep names short and constant.
  • JankStats needs JankStats.createAndTrack(window, listener), and you should toggle isTrackingEnabled in onResume/onPause. Add UI state with PerformanceMetricsState.getHolderForHierarchy(view).state?.putState(...).
  • Profile a release-like build. Debuggable builds run slower (less optimised code, extra checks), so jank in a debug build may not exist in release. Use a profileable release build, enabled with <profileable android:shell="true" /> in the manifest.
  • In Jetpack Compose, reading fast-changing state (scroll offset, animation value) during composition makes the whole function recompose every frame. Read it in a lambda modifier (Modifier.offset { }, graphicsLayer { }) or wrap derived values in derivedStateOf.
  • Test on the devices your users actually have. A mid-range phone often shows jank that a flagship hides.

Code example

This Activity tracks janky frames with JankStats and tags them with the current screen, and the adapter wraps its binding in an androidx.tracing section so it shows as a named slice in a Perfetto trace.

import androidx.metrics.performance.JankStats
import androidx.metrics.performance.PerformanceMetricsState
import androidx.tracing.trace
 
class FeedActivity : AppCompatActivity() {
    private lateinit var jankStats: JankStats
 
    private val jankFrameListener = JankStats.OnFrameListener { frameData ->
        if (frameData.isJank) {
            // A real app would batch these and send them to analytics
            Log.w("Jank", "Janky frame: ${frameData.frameDurationUiNanos / 1_000_000} ms, ${frameData.states}")
        }
    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_feed)
 
        val holder = PerformanceMetricsState.getHolderForHierarchy(window.decorView)
        jankStats = JankStats.createAndTrack(window, jankFrameListener)
        holder.state?.putState("Screen", "Feed")
    }
 
    override fun onResume() {
        super.onResume()
        jankStats.isTrackingEnabled = true
    }
 
    override fun onPause() {
        super.onPause()
        jankStats.isTrackingEnabled = false
    }
}
 
class FeedAdapter : ListAdapter<FeedItem, FeedViewHolder>(FeedDiff) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FeedViewHolder =
        FeedViewHolder.create(parent)
 
    override fun onBindViewHolder(holder: FeedViewHolder, position: Int) {
        // Shows up as a "Feed:bind" slice on the main thread in Perfetto
        trace("Feed:bind") {
            holder.bind(getItem(position))
        }
    }
}
  • JankStats.createAndTrack reports every frame; the listener only logs frames flagged isJank, with the UI states that were active.
  • Tracking is turned off in onPause so frames are not reported while the screen is not visible.
  • In a Perfetto trace, long Feed:bind slices inside a late Choreographer#doFrame tell you binding is the problem; short ones send you to layout, RenderThread or locks instead.

Run the idea in plain Kotlin

class FrameBudget(val hz: Int) {
  val budgetMs: Double = 1000.0 / hz.toDouble()
  fun isJank(durationMs: Double): Boolean = durationMs > budgetMs
}

fun fmt(x: Double): String = String.format(java.util.Locale.ROOT, "%.1f", x)

fun report(label: String, durations: List<Double>, budget: FrameBudget) {
  val janky = durations.filter { budget.isJank(it) }
  val worst = durations.maxOrNull() ?: 0.0
  println(label + ": budget " + fmt(budget.budgetMs) + " ms")
  println("  frames=" + durations.size + " janky=" + janky.size +
      " worst=" + fmt(worst) + " ms (" + fmt(worst - budget.budgetMs) + " ms over)")
}

fun main() {
  // Simulated frame durations in ms during one scroll
  val durations = listOf(
      6.5, 7.2, 9.1, 33.4, 8.0,
      12.3, 50.1, 7.9, 15.0, 6.8
  )
  report("60 Hz", durations, FrameBudget(60))
  report("120 Hz", durations, FrameBudget(120))
}

Expected output:

60 Hz: budget 16.7 ms
  frames=10 janky=2 worst=50.1 ms (33.4 ms over)
120 Hz: budget 8.3 ms
  frames=10 janky=5 worst=50.1 ms (41.8 ms over)

In production

Feed scroll jank on mid-range devices
  • JankStats data sent to analytics showed most janky frames tagged with the Feed screen state, mainly on mid-range 60 Hz devices.
  • A Perfetto trace of a scroll showed long Feed:bind slices inside late Choreographer#doFrame slices. Inside them, BitmapFactory.decodeFile was decoding full-size thumbnails on the main thread.
  • The item layout was also several levels of nested LinearLayout with weights, which made measure and layout slow for each new row.
The fix
  • Replaced manual decoding with an image loading library (Coil) that decodes off the main thread at the target view size and caches results.
  • Flattened the item layout into a single ConstraintLayout.
  • Added a Macrobenchmark scroll test with FrameTimingMetric so frame time regressions on the feed show up in CI on a test device. The new trace showed Feed:bind slices well inside the frame budget.
Compose screen recomposing on every scroll frame
  • A Compose list screen stuttered while scrolling, and the Layout Inspector's recomposition counts showed the whole screen recomposing on every frame.
  • The screen read listState.firstVisibleItemIndex at the top level to decide whether to show a "scroll to top" button, so every scroll change invalidated the whole screen's composition.
  • The Perfetto trace showed long Recomposer and composition work in most Choreographer#doFrame slices during scrolling.
The fix
  • Wrapped the check in val showButton by remember { derivedStateOf { listState.firstVisibleItemIndex > 0 } }, so only the change from false to true (or back) triggers recomposition.
  • Moved the button into its own small composable that reads showButton, keeping the list itself out of that recomposition.
  • Recomposition counts during scroll dropped to only the list items entering the screen, and the trace no longer showed composition work in most frames.

Common mistakes

  • Profiling only on a flagship device. Code that fits the budget on a fast chip can miss it on a mid-range one. Profile on devices that match your users; Play Console shows your device distribution.
  • Measuring frames with timestamps in your own loop. Wall-clock timing in a loop does not line up with vsync and misses work on the RenderThread. Use JankStats, FrameTimingMetric or a Perfetto trace.
  • Looking only at the main thread in a trace. If the main thread finished early but the frame was still late, the time went to the RenderThread, the GPU, a lock, or the system. Check the RenderThread track and the Actual Timeline jank type.
  • Assuming every late frame is the app's fault. On Android 12+ the frame timeline jank type tells you whether the app missed its deadline or the system (SurfaceFlinger, display) did. Fix the side that was actually late.
  • Profiling a debuggable build. Debuggable builds run slower and show jank that release does not have. Use a profileable release build.
  • Not tying jank to a screen or action. A global jank count is hard to act on. Add JankStats states for the screen and action (scrolling, animating), and named trace sections around suspect code.

Interview questions

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

“What is jank in Android and what are the most common causes?”

“Explain the Android frame pipeline from vsync to display.”

“How do you use Perfetto to diagnose a jank issue?”

“What is JankStats and when would you use it instead of a Perfetto trace?”

Quiz

At 120 Hz, what is the frame budget in milliseconds?

Which tool reports janky frames from real users in production, with UI state attached?

A Perfetto trace shows a short Choreographer#doFrame slice on the main thread, but the frame is still late. Where should you look next?

How do you add a named section around your own code so it appears in a Perfetto trace?

0 of 4 answered

Mini task

15-minute exercise: capture and read a jank trace

  1. Make a profileable release build. Add <profileable android:shell="true" /> inside <application> in your manifest (with tools:targetApi="29"). For local testing, let the release build use the debug signing config so you can install it. Install it on a physical device.

  2. Add a trace section. Add the androidx.tracing:tracing-ktx dependency. In the onBindViewHolder of your most complex RecyclerView adapter (or around a heavy composable's work), wrap the body:

    trace("Feed:bind") {
        holder.bind(getItem(position))
    }
  3. Capture a trace. In Android Studio's profiler, start a system trace recording of your app (the "Capture System Activities" option), or run adb shell perfetto -o /data/misc/perfetto-traces/trace.perfetto-trace -t 10s sched freq gfx view input and then adb pull the file. Scroll the list quickly during the recording.

  4. Read the trace. Open it in Android Studio or ui.perfetto.dev. Find your app's process, the late frames in the Actual Timeline (Android 12+), and the Feed:bind slices inside Choreographer#doFrame on the main thread. Note whether long frames are long because of binding, layout, RenderThread work, or blocking.

  5. Add JankStats. Add androidx.metrics:metrics-performance, set up JankStats.createAndTrack as in the example, scroll again, and count the janky frames logged for the screen.

  6. Fix one source. Take the longest slice inside the late frames and move or remove its work: decode images off the main thread, flatten the layout, or cache a computed value. Capture a new trace.

Done condition: in the new trace the Feed:bind slices fit inside the frame budget for your device's refresh rate, and JankStats logs fewer janky frames for the same scroll than before the fix.

Next: Battery and network efficiency