如何使用 Jetpack Compose 提高性能(在 @Composable 函数中组装某些东西时)

How to Improve performance with Jetpack Compose (when assembling something inside a @Composable function)

假设我的应用程序中有两个可组合项:

@Composable
fun CoreKeyboard(keyboardKeys: List<List<KeyboardKey>>, ...) {
    // ...
}

@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, ...)

}

如果我没记错的话,这种方法不是很有效,因为在每次重组中 NumberKeyboard 中的 keyboardKeys 都会被重新组合。

最好的方法是什么?

我考虑过使用 by remember { mutableStateOf(...) },但 keyboardKeys 是不可变的。这仍然是一个好方法吗?

如果您有一些计算成本很高的东西,并且只想在您的可组合项上计算一次,只需用 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"))
    )
}

如果你想改变值以便观察它,你只需要 mutableStateOf