Sometimes I want to provide an optional lambda to ...
# general-advice
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.
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: If you search, you'll find various other reports on the subject too.
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.
Keep us posted!