Search code examples
androidkotlinandroid-jetpack-compose

Is the event lambda necessary? Will it affect performance?


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")
    }
}

Solution

  • 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

    Image 1

    NoLamdba Output

    Image 2

    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.