https://kotlinlang.org logo
#compose
Title
# compose
k

K Merle

08/25/2022, 5:35 AM
Does it make a difference if, in a composable function, you declare lambda first, and pass it as an argument, or directly pass it as an argument?
Copy code
@Composable
fun Parent() {
    val argument = {
        // Do something
    }
    Child(param = argument)
}

fun Child(param: () -> Unit) {}
vs
Copy code
@Composable
fun Parent() {
    Child(param = {
        // Do something
    })
}

fun Child(param: () -> Unit) {}
m

MR3Y

08/25/2022, 10:26 AM
You might go with option one but you should wrap it in a
remember{}
when you want to memoize a non-stable variable capturing lambda, so you memoize it to avoid a lot of unnessecary recompositions Jetpack compose performane gotchas, Option 2: remembered lambdas, otherwise i would just stick with option 2
k

K Merle

08/25/2022, 12:27 PM
But it does not make a difference I think version 1 or 2, both of these are re-declared once created?
m

MR3Y

08/25/2022, 12:39 PM
No, there is a difference! I suggest you to take a look at this twitter thread: https://twitter.com/shikasd_/status/1555754156346015744 to see the underlying representation of lambdas on JVM and how does the compose compiler optimize those (when it knows what lambdas to optimize!)
k

K Merle

08/25/2022, 12:40 PM
Will take a look, thank you.
m

MR3Y

08/25/2022, 12:40 PM
Also, notice that I'm saying you should WRAP the lambda in a
remember{}
in order to memoize it, otherwise I believe there is no difference
l

Leland Richardson [G]

08/25/2022, 1:51 PM
assuming the body of the lambda is the same, it should not make any difference. if you notice somewhere that it does, please file a bug
4 Views