CoursesAndroid from the foundation

Practice chapter 4 of 7

Pixels, collection and retained objects

Spend one display interval

A frame callback coordinates work with display timing. UI work records or updates drawing commands, rendering work is submitted and the GPU processes it before display composition. CPU and GPU work can overlap across frames, so adding all thread durations does not by itself predict presentation.

Worked example

At 120 Hz the interval is about 8.33 ms. A 12 ms main-thread layout beginning at the frame opportunity already exceeds one interval even if GPU work is cheap. Inspect the trace to locate the missed deadline.

Try it

If profiling shows 3 ms of GPU activity for that frame, would lowering shader cost alone fix the 12 ms layout?

Compare your answer

It would leave the identified main-thread cost. Inspect layout and scheduling first, then compare actual presentation deadlines after the change.

Source · Android · Slow rendering

Read state in the phase that needs it

Compose tracks state reads in composition, layout and drawing. A changed value can restart work from the phase that consumed it. Composition describes nodes, layout measures and places them, and drawing produces pixels.

Worked example

A background color read inside a draw lambda can invalidate drawing without needing to measure text again. A new text string consumed during composition may change its size and require layout. Inspect where the state value is actually read.

Try it

A drag changes only placement. What experiment would distinguish composition work from placement work?

Compare your answer

Compare reading position while constructing the modifier with reading it inside a placement lambda. Keep the gesture constant and inspect recomposition counts plus frame timing.

Source · Android · Jetpack Compose phases

Separate garbage from a leak

The managed collector can reclaim objects that no longer have a path from a root. Short-lived allocations can still raise collection frequency. A leaked Activity is reachable even though the product no longer needs it, so repeated collections cannot solve that retention.

Worked example

Repeated screen rotations create five old editor instances. A heap dump shows a singleton listener registry pointing to all five. Remove registrations on disposal, repeat the rotations and compare the retaining paths and instance counts.

Try it

What if old editors disappear but allocation rate remains high during drawing?

Compare your answer

That suggests churn on the drawing path, a different mechanism. Record allocations during the same gesture to find objects recreated per frame.

Source · Android Studio · Capture a heap dump