Jetpack compose list performance recomposition counts

1.2k Views Asked by At

I notice ( i know it is not good to test in debug mode ) that my app has very laggy scroll and than i look into layout inspector and try to count recomposition. I see for example that for some post recomposition occurs 5 times or even 8. Can this actually heavily affect my app performance? here is image showing layout inspectorenter image description here

1

There are 1 best solutions below

0
zaifrun On

It depends on what your expected recomposition counts should be. Recomposition in itself is not bad, in fact it is necessary to update the UI.

But you should not have unneccessary recompositions occur as this will be bad for performance.

From your screenshot it is difficult to say if these numbers are high or not. For instance is the screenshot taken after entering a specific screen for the first time, then maybe 5 seems high, but again it depends on your specific code and how many recompositions you expected in this specific screen.

I try to do a logical calculation myself of approximately how many recompositions I would expect of a particular critical UI element (such as a list etc) and then compare with the layout inspector. If the count in the layout inspector is much higher than I expected, then in a lot of cases my code was not optimal in terms of UI updates.

One concrete performance issue to watch out for with lists in Jetpack compose, is that you need to be careful about loading the data for the list inside a Composable. Let's say you want to load the data from a database from your ViewModel that calls a database load from your Repository using a coroutine and you want to load this data inside a Composable function. Here you should use the SideEffects to make sure data is only loaded once and not on recompositions (if the data does not change). One way to do this is to use produceState:

//empty defined elsewhere
 val myData by produceState(initialValue = empty) 
     {
         viewModel.getData().observe(lifeCycleOwner) 
         {
             value = it
         }
     }

See the documentation for more info.