Prefer Function Reference over Lambda in Kotlin? Wrong!
You may think Kotlin function reference runs faster than Kotlin lambda, but wrong! In fact, Kotlin lambda runs 2x faster!
Using lambda as callback is very common in Jetpack compose, but do you know you can also use function reference to replace the lambda?
When I first heard about this function reference, I thought the function reference must be better. Unlike anonymous function / lambda, it just a function pointer or reference to a function. It should run faster and use less memory, as it doesn’t allocate extra memory. So I replaced lambda with function reference whenever is possible. Well, I was wrong!
After doing some researches, it turns out that function reference still allocates extra memory just like what lambda does, and it also runs 2x slower than lambda. Before we look into why, let’s understand their usages and differences first with examples below.
Lambda (call the object’s function)
Let’s say you have Screen
and ViewModel
classes below. The id
is used to identify a different instance of ViewModel
.
class Screen(private val callback: () -> Unit) {
fun onClick() = callback()
}
class ViewModel(var id…