In a Composable, Usually we use function param to handle the event, such as the following onClickHandler: () -> Unit
In the official documentation, using a lambda to call this onClickHandler
function.
@Composable
fun FilledButtonExample(onClickHandler: () -> Unit) {
Button(onClick = { onClickHandler() }) {
Text("Filled")
}
}
Is it better if we assign the onClickHandler
function directly to the onClick
variable? such as Button(onClick = onClickHandler )
@Composable
fun FilledButtonExample(onClickHandler: () -> Unit) {
Button(onClick = onClickHandler ) {
Text("Filled")
}
}
Removing the redundant lamdba will be better, but the impact on performance will be neglegible.
Let's run a test to see if the compiled output of the two variants is actually different, as the Kotlin Compiler does many optimizations to remove redundancy.
I built two minimal code samples that are anough to test the case:
Lambda.kt
fun main() {
val onClickHandler: () -> Unit = { println("Hello World") }
val onClick: () -> Unit = { onClickHandler() }
onClick()
}
NoLambda.kt
fun main() {
val onClickHandler: () -> Unit = { println("Hello World") }
val onClick: () -> Unit = onClickHandler
onClick()
}
We can compile a Kotlin file with the following command:
kotlinc Lamdba.kt -d Lambda
When we compare the outputs, we see the following:
Lamdba Output
NoLamdba Output
The Kotlin Compiler generates a separate class file for each function. So by omitting the redundant lamdba, we actually reduce the number of generated class files.
The practical impact on performance will be neglegible though.