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!

This article was originally published at vtsen.hashnode.dev on Sep 10, 2022.

Using lambda as callback is very common in Jetpack …

You may think Kotlin function reference runs faster than Kotlin lambda, but wrong! In fact, Kotlin lambda runs 2x faster!

This article was originally published at vtsen.hashnode.dev on Sep 10, 2022.

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: String) {
    fun screenOnClick() {
        println("ViewModel$id onClick() is called!")
    }

    fun screenOnClickDoNothing() {}
}

In main(), it creates the ViewModel object. Then, you pass in the lambda callback parameter – { viewModel.screenOnClick() } to Screen‘s constructor.

fun main() {
    var viewModel = ViewModel("1")
    val screen = Screen {
        viewModel.screenOnClick()
    }
    viewModel = ViewModel("2")
    screen.onClick()
}

viewModel.screenOnClick() is the object’s function.

To demonstrate the difference between lambda and function reference, you update the viewModel variable with another new instance of ViewModelviewModel = ViewModel("2") before calling screen.onClick().

Calling screen.onClick() is to simulate screen callback

Here is the output:

ViewModel2 onClick() is called!

Please note that ViewModel2 is called instead of ViewModel1. It looks like lambda holds the reference to the viewModel variable. When the variable is updated, it is automatically reflected.

Object’s Function Reference

Let’s replace the lambda with a function reference – viewModel::screenOnClick. The code looks like this.

fun main() {
    var viewModel = ViewModel("1")
    val screen = Screen(callback = viewModel::screenOnClick)
    viewModel = ViewModel("2")
    screen.onClick()
}

Here is the output

ViewModel1 onClick() is called!

Please note that ViewModel1 is called instead of ViewModel2. It looks like the function reference is caching the ViewModel instance when it is called. Thus, it is the old ViewModel instance and not the updated one. Wrong!

If you don’t replace the viewModel instance but modifying ViewModel.id directly instead,

fun main() {
    var viewModel = ViewModel("1")
    val screen = Screen(callback = viewModel::screenOnClick)
    viewModel.id = "2"
    screen.onClick()
}

you get the updated value.

ViewModel2 onClick() is called!

This tells you that function reference doesn’t cache the ViewModel instance, but holding its reference. If the original viewModel is replaced, the Screen still holds the old reference of the ViewModel. Thus, it prints out the value of that old reference.

Performance Test (Object’s Function)

Let’s run some performance tests.

This is the lambda test that creating Screen 1 billions times.

fun lambdaTest() {
    val viewModel = ViewModel("1")

    val timeMillis = measureTimeMillis {
        repeat(1_000_000_000) {
            val screen = Screen {
                viewModel.screenOnClickDoNothing()
            }

            screen.onClick()
        }
    }
    println("lambdaTest: ${timeMillis/1000f} seconds")
}

The output show it runs ~2.4 seconds.

lambdaTest: 2.464 seconds

Now, it is function reference’s turn.

fun funRefTest() {

    val viewModel = ViewModel("1")

    val timeMillis = measureTimeMillis {
        repeat(1_000_000_000) {
            val screen = Screen(
                callback = viewModel::screenOnClickDoNothing
            )

            screen.onClick()
        }
    }
    println("funRefTest: ${timeMillis/1000f} seconds")
}

The output shows it runs 5.2 seconds.

funRefTest: 5.225 seconds

This concludes that lambda runs ~2x faster than function reference. Why? Let’s look at the decompiled code.

Decompiled Code In Java

Let’s look at the decompiled code in Java. This is the simplified version without the measureTimeMillis and repeat code.

lambdaTest()

public static final void lambdaTest() {
  final ViewModel viewModel = new ViewModel();
  Screen screen = new Screen((Function0)(new Function0() {

     public Object invoke() {
        this.invoke();
        return Unit.INSTANCE;
     }

     public final void invoke() {
        viewModel.screenOnClickDoNothing();
     }
  }));
  screen.onClick();
}

funRefTest()

public static final void funRefTest() {
  ViewModel viewModel = new ViewModel();
  Screen screen = new Screen((Function0)(new Function0(viewModel) {

     public Object invoke() {
        this.invoke();
        return Unit.INSTANCE;
     }

     public final void invoke() {
        ((ViewModel)this.receiver).screenOnClickDoNothing();
     }
  }));
  screen.onClick();
}

Few important things here:

  • Function reference allocates new function memory just like the lambda – new Function0() and new Function0(viewModel). So it is not a function pointer.
  • Function reference passes in the viewModel into Function0 and lambda doesn’t

Based on these findings, I suspect the passed-in ViewModel reference could be the overhead (requires extra copy to hold the reference?) that contributes to slowness in function reference.

What about non-object’s function?

Let’s say you move screenOnClickDoNothing() out of ViewModel

fun screenOnClickDoNothing() {}

and call it directly – replace viewModel.screenOnClickDoNothing() with screenOnClickDoNothing() in lambda.

fun lambdaTest() {
    val timeMillis = measureTimeMillis {
        repeat(1_000_000_000) {
            val screen = Screen {
                screenOnClickDoNothing()
            }

            screen.onClick()
        }
    }
    println("lambda1Test: ${timeMillis/1000f} seconds")
}

It takes 0.016 seconds to run.

lambdaTest: 0.016 seconds

What about function reference? Replace viewModel::screenOnClickDoNothing with ::screenOnClickDoNothing

fun globalFunRefTest(){
    val timeMillis = measureTimeMillis {
        repeat(1_000_000_000) {
            val screen = Screen(callback = ::screenOnClickDoNothing)
            screen.onClick()
        }
    }
    println("funRefTest: ${timeMillis/1000f} seconds")
}

and it takes the same amount of time as lambda.

funRefTest: 0.016 seconds

It makes senses because both have the same exact decompiled Java code.

public static final void lambdaTest() {
    Screen screen = new Screen((Function0)null.INSTANCE);
    screen.onClick();
}

public static final void funRestTest() {
    Screen screen = new Screen((Function0)null.INSTANCE);
    screen.onClick();
}

One important thing to note is, although lambda is used, there is no new function memory allocated. Maybe the compiler is smart enough to optimize it. Thus, it runs faster than lambda with object’s function in the previous examples.

By the way, all the tests I ran so far is based on Kotlin compiler version 1.7.10.

Conclusion

There is a slight different behavior between using lambda vs function reference, but I don’t see any practical use case to use either one of them. By guessing, I think lambda should cover 99% of use cases because it doesn’t require the object to be initialized first while registering the callback.

Here is the summary of Lambda vs Function Reference behavior:

Lambda Function Reference
Keeps the up-to-date object reference Keeps the copy of the object reference
Does NOT require the object to be initialized Requires the object to be initialized

Calling the function 1 billions times may not be practical, but it does prove that function reference is NOT better than lambda in Kotlin. Practically, it probably doesn’t matter which one you use. The difference is likely negligible.

Maybe because I’m coming for C++/C# background, I had an impression that function reference in Kotlin is like a function pointer. You hold the reference to the function, and you do not allocate new memory. No, it is not the case in Kotlin.

Given this very little research I did, I’ve decided to use lambda over function reference to implement callbacks because it has less overhead. It also doesn’t reduce readability too much, in my opinion. Just the extra { }?

[Updated – Sept 27, 2022]: I take back my word. I do find lamba is a bit less readable especially the lambda has arguments while working on this project.

See Also


Print Share Comment Cite Upload Translate
APA
Vincent Tsen | Sciencx (2024-03-29T10:18:04+00:00) » Prefer Function Reference over Lambda in Kotlin? Wrong!. Retrieved from https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/.
MLA
" » Prefer Function Reference over Lambda in Kotlin? Wrong!." Vincent Tsen | Sciencx - Saturday October 1, 2022, https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/
HARVARD
Vincent Tsen | Sciencx Saturday October 1, 2022 » Prefer Function Reference over Lambda in Kotlin? Wrong!., viewed 2024-03-29T10:18:04+00:00,<https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/>
VANCOUVER
Vincent Tsen | Sciencx - » Prefer Function Reference over Lambda in Kotlin? Wrong!. [Internet]. [Accessed 2024-03-29T10:18:04+00:00]. Available from: https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/
CHICAGO
" » Prefer Function Reference over Lambda in Kotlin? Wrong!." Vincent Tsen | Sciencx - Accessed 2024-03-29T10:18:04+00:00. https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/
IEEE
" » Prefer Function Reference over Lambda in Kotlin? Wrong!." Vincent Tsen | Sciencx [Online]. Available: https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/. [Accessed: 2024-03-29T10:18:04+00:00]
rf:citation
» Prefer Function Reference over Lambda in Kotlin? Wrong! | Vincent Tsen | Sciencx | https://www.scien.cx/2022/10/01/prefer-function-reference-over-lambda-in-kotlin-wrong/ | 2024-03-29T10:18:04+00:00
https://github.com/addpipe/simple-recorderjs-demo