简体   繁体   English

Jetpack Compose 列表性能重组计数

[英]Jetpack compose list performance recomposition counts

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?例如,我看到某些后期重组发生了 5 次甚至 8 次。这真的会严重影响我的应用程序性能吗? here is image showing layout inspector这是显示布局检查器的图像在此处输入图像描述

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.重构本身并没有什么不好,其实是更新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.例如是第一次进入特定屏幕后截取的屏幕截图,那么 5 似乎很高,但这同样取决于您的特定代码以及您在该特定屏幕中期望的重组次数。

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.我尝试自己对特定关键 UI 元素(例如列表等)大约期望进行多少次重组进行逻辑计算,然后与布局检查器进行比较。 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.如果布局检查器中的计数比我预期的高很多,那么在很多情况下,我的代码在 UI 更新方面并不是最佳的。

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. Jetpack compose 中的列表需要注意的一个具体性能问题是,您需要小心地将列表的数据加载到 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).假设您想从 ViewModel 的数据库中加载数据,ViewModel 使用协程从您的 Repository 调用数据库加载,并且您想将此数据加载到 Composable function 中。在这里,您应该使用 SideEffects 来确保只加载数据一次而不是重组(如果数据没有改变)。 One way to do this is to use produceState:一种方法是使用 produceState:

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

See the documentation for more info.有关详细信息,请参阅文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM