[英]How to Improve performance with Jetpack Compose (when assembling something inside a @Composable function)
Suppose I have two composables in my app:假设我的应用程序中有两个可组合项:
@Composable
fun CoreKeyboard(keyboardKeys: List<List<KeyboardKey>>, ...) {
// ...
}
and和
@Composable
fun NumberKeyboard(...) {
val keyboardKeys = listOf(
listOf(KeyboardKey("1"), KeyboardKey("2"), KeyboardKey("3")),
listOf(KeyboardKey("4"), KeyboardKey("5"), KeyboardKey("6")),
listOf(KeyboardKey("7"), KeyboardKey("8"), KeyboardKey("9")),
listOf(KeyboardKey("0"))
)
CoreKeyboard(keyboardKeys = keyboardKeys, ...)
}
If I'm not wrong, this approach is not very performatic as in every recomposition the keyboardKeys
in NumberKeyboard
will be reassembled.如果我没记错的话,这种方法的性能不是很好,因为在每次重组中NumberKeyboard
中的keyboardKeys
键都会被重新组装。
What is the best way to do this?做这个的最好方式是什么?
I thought about using by remember { mutableStateOf(...) }
, but keyboardKeys
is immutable.我考虑过使用by remember { mutableStateOf(...) }
,但keyboardKeys
是不可变的。 Is it still a good approach?它仍然是一个好方法吗?
If you have something that is expensive to compute and you want to compute it on your composable only once, simply wrap it with remember
如果你有一些计算起来很昂贵的东西,并且你只想在你的可组合上计算它一次,只需用remember
包装它
val keyboardKeys = remember {
listOf(
listOf(KeyboardKey("1"), KeyboardKey("2"), KeyboardKey("3")),
listOf(KeyboardKey("4"), KeyboardKey("5"), KeyboardKey("6")),
listOf(KeyboardKey("7"), KeyboardKey("8"), KeyboardKey("9")),
listOf(KeyboardKey("0"))
)
}
You only need the mutableStateOf
if you want to mutate the value so that it can be observed.如果你想改变值以便观察它,你只需要mutableStateOf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.