Blog Infos
Author
Published
Topics
Author
Published

Improving Jetpack Compose performance with Compose Compiler Metrics

subprojects {
    tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
        kotlinOptions {
            if (project.findProperty("musicApp.enableComposeCompilerReports") == "true") {
                freeCompilerArgs += [
                        "-P",
                        "plugin:androidx.compose.compiler.plugins.kotlin:reportsDestination=" +
                                project.buildDir.absolutePath + "/compose_metrics"
                ]
                freeCompilerArgs += [
                        "-P",
                        "plugin:androidx.compose.compiler.plugins.kotlin:metricsDestination=" +
                                project.buildDir.absolutePath + "/compose_metrics"
                ]
            }
        }
    }
}
{
 "skippableComposables": 147,
 "restartableComposables": 156,
 "readonlyComposables": 0,
 "totalComposables": 168,
}
restartable scheme("[androidx.compose.ui.UiComposable]") fun AlbumScreen(
 unstable screenState: PlayerScreenState
 stable playbackData: PlaybackData
 stable sharedProgress: Float
 stable onBackClick: Function0<Unit>
 stable onInfoClick: 
   Function4<@[ParameterName(name = 'info')] ModelAlbumInfo,
     @[ParameterName(name = 'offsetX')] Float,
     @[ParameterName(name = 'offsetY')] Float,
     @[ParameterName(name = 'size')] Int, Unit>
)
unstable class PlayerScreenState {
 stable val density: Density
 stable var maxContentWidth: Int
 stable var maxContentHeight: Int
 stable val easing: Easing
 stable var currentScreen$delegate: MutableState<Screen>
 stable var currentDragOffset$delegate: MutableState<Float>
 stable val songInfoContainerHeight: Int
 stable val playerContainerHeight: Int
 stable val songInfoContentHeight: Int
 stable val albumContainerHeight: Int
 stable val albumImageWidth: Dp
 stable val commentsContainerHeight: Int
 stable val backHandlerEnabled$delegate: State<Boolean>
 stable val fromPlayerControlsToAlbumsListProgress$delegate: State<Float>
 stable val playerControlOffset$delegate: State<Float>
 stable val commentsListOffset$delegate: State<Int>
 stable val songInfoOffset$delegate: State<Float>
 stable val albumsInfoSize: Dp
 stable val photoScale$delegate: State<Float>
 <runtime stability> = Unstable
}
@Stable
class PlayerScreenState(
   constraints: Constraints,
   private val density: Density,
   isInPreviewMode: Boolean = false,
) {
   //...
}

Next, we clear the cache and build again to see how the result has changed. We again open the app_release-composables.csv table, and find restartable but not skippable methods. After our changes the number of such functions has decreased, so the @Stable annotation helped.

Next, we’ll look at other composables. One main problem stands out: Collections.

restartable scheme("[androidx.compose.ui.UiComposable]") fun AlbumsListContainer(
 stable modifier: Modifier? = @static Companion
 stable listScrollState: ScrollState? = @dynamic rememberScrollState(0, $composer, 0, 0b0001)
 unstable albumData: Collection<ModelAlbumInfo>
 stable albumImageWidth: Dp = @static 150.dp
 stable transitionAnimationProgress: Float = @static 0.0f
 stable appearingAnimationProgress: Float = @static 1.0f
 stable onBackClick: Function0<Unit>? = @static {}
 stable onShareClick: Function0<Unit>? = @static {}
@Stable
@Immutable
data class ModelAlbumInfo(
   @DrawableRes val cover: Int,
   val title: String,
   val author: String,
   val year: Int,
-  val songs: List<ModelSongInfo>,
+  val songs: ImmutableList<ModelSongInfo>,
)
- private val songs = listOf(
+ private val songs = persistentListOf(
      ModelSongInfo(0L, "Aurora", "All Is Soft Inside", "3:54"),
      ModelSongInfo(1L, "Aurora", "Queendom", "5:47"),
      ModelSongInfo(2L, "Aurora", "Gentle Earthquakes", "4:32"),
      ModelSongInfo(3L, "Aurora", "Awakening", "6:51"),
      ModelSongInfo(4L, "Aurora", "All Is Soft Inside", "3:54"),
      ModelSongInfo(5L, "Aurora", "Queendom", "5:47"),
)

In addition to List, there is a problem with the SectionSelector function that renders tabs:

restartable scheme("[androidx.compose.ui.UiComposable]") fun SectionSelector(
  stable modifier: Modifier? = @static Companion
  unstable sections: Collection<Section>
  unstable selection: Section
  stable onClick: Function1<Section, Unit>? = @static { it: Section -> }
)

Let’s take a closer look at its implementation:

@Composable
fun SectionSelector(modifier: Modifier = Modifier, onSelect: (Section) -> Unit = {}) {
   val sectionTitles = remember {
       listOf(
           Section("Comments"),
           Section("Popular"),
       )
   }
   var currentSelection by remember { mutableStateOf(sectionTitles.last()) }

   SectionSelector(
       modifier = modifier,
       sections = sectionTitles,
       selection = currentSelection,
       onClick = { selection ->
           if (selection != currentSelection) {
               currentSelection = selection
               onSelect(selection)
           }
       }
   )
}

We see that the function is just a wrapper that contains a list and the current tab selection logic. We can get rid of this function by moving these elements into the next function in the hierarchy and therefore get rid of the non-skippable function.
Let’s gather the compiler statistics again. Now, there aren’t any restartable but skippable composables, which is great!

{
 "skippableComposables": 155,
 "restartableComposables": 155,
 "readonlyComposables": 0,
 "totalComposables": 167,
}
restartable skippable scheme("[androidx.compose.ui.UiComposable, [androidx.compose.ui.UiComposable]]") fun RoundedCornersSurface(
 stable modifier: Modifier? = @static Companion
 stable topPadding: Dp = @static 0.dp
 stable elevation: Dp = @static 0.dp
 stable color: Color = @dynamic MaterialTheme.colors.surface
 stable content: @[ExtensionFunctionType] Function3<BoxScope, Composer, Int, Unit>
)

The second case is the use of remember. In our case, we remember the state of the scroll:

restartable skippable scheme("[androidx.compose.ui.UiComposable]") fun CommentsList(
 stable modifier: Modifier? = @static Companion
 stable scrollState: ScrollState? = @dynamic rememberScrollState(0, $composer, 0, 0b0001)
 stable comments: ImmutableList<ModelComment>
 stable onActionClick: Function1<Action, Unit>? = @static { it: Action -> }
 stable topPadding: Dp = @static 0.dp
)

In all other cases where the default parameter is marked with @dynamic, you should try to get rid of the default values or use the @Stable annotation. For example, in the NowPlayingAlbumScreen function the parameter insets is marked as @dynamic.

@Composable
fun NowPlayingAlbumScreen(
   insets: DpInsets = DpInsets.Zero,
)

Let’s annotate it with @Stable to show the compiler that this parameter is stable by default.

companion object {
   @Stable
   fun from(topInset: Dp, bottomInset: Dp) = DpInsets(DpSize(topInset, bottomInset))
 
+  @Stable
   val Zero: DpInsets get() = DpInsets(DpSize.Zero)
}

Another case in this project was specifying a default parameter to recompose a function as a unit. In this case we just get rid of the default parameter.

@Composable
@Stable
fun rememberCollapsingHeaderState(
-   key: Any = Unit,
+   key: Any,
    topInset: Dp
) = remember(key1 = key) {
    CollapsingHeaderState(topInset = topInset)
}

Yet another case occurred when a default parameter was specified as a different default parameter from the same function.

@Composable
fun AnimatedVolumeLevelBar(
    modifier: Modifier = Modifier,
    barWidth: Dp = 2.dp,
-   gapWidth: Dp = barWidth,
+   gapWidth: Dp = 2.dp,
    barColor: Color = MaterialTheme.colors.onPrimary,
    isAnimating: Boolean = false,
)

After:

Job Offers

Job Offers

There are currently no vacancies.

OUR VIDEO RECOMMENDATION

,

Jetpack Compose: Drawing without pain and recomposition

This is a talk on recomposition in Jetpack Compose and the myths of too many calls it is followed by. I’ll briefly explain the reasons behind recompositions and why they are not as problematic as…
Watch Video

Jetpack Compose: Drawing without pain and recomposition

Vitalii Markus
Android Engineer
Flo Health Inc.

Jetpack Compose: Drawing without pain and recomposition

Vitalii Markus
Android Engineer
Flo Health Inc.

Jetpack Compose: Drawing without pain and recomposition

Vitalii Markus
Android Engineer
Flo Health Inc.

Jobs

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog
In the world of Jetpack Compose, where designing reusable and customizable UI components is…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE
Menu