https://kotlinlang.org logo
Title
l

Landry Norris

06/21/2022, 5:40 PM
Sometimes I want to provide an optional lambda to a method. From a performance standpoint, is it better to make the lambda nullable and check
if(lambda != null) lambda()
or will I get better performance setting
lambda = {}
by default and always calling it? I get that both should be fast, but I’d like to minimize overhead in a hot spot. This code is for both K/JVM and K/Native.
k

Klitos Kyriacou

06/22/2022, 9:22 AM
You should measure the performance in your own application, on the target machine and with the compiler/runtime version that will be used in production, since different environments can give different results. My hunch is that checking a null lambda would be prone to branch misprediction, which is expensive, so I would favour the empty lambda idea. However, someone has already tested these two scenarios, albeit in an old version of Java, back in 2015, and found varying results: https://stackoverflow.com/questions/22890326/is-defaulting-to-an-empty-lambda-better-or-worse-than-checking-for-a-potentially. If you search, you'll find various other reports on the subject too.
l

Landry Norris

06/22/2022, 2:29 PM
Thanks. I noticed when I looked through some source code in Compose that they had some global variables set to empty lambdas, with a note about how it’s faster than passing in an empty lambda literal. I can see how the C2 compiler for JVM would make nullable faster (that was one of the C2's optimizations if I remember correctly). I wonder how native will be affected. I’ll have to write some experimental code to test at some point.
s

Sam Stone

08/15/2022, 4:59 AM
Keep us posted!