When you assign a function as a value, the created object is an instance of one of the function classes ( Function1 if it takes one argument, Function2 if it takes two arguments, etc.). In fact, a function call is a call to the apply method on a FunctionN object.
In this regard, there is actually very little overhead if you are not looking at the critical cycle. Theoretically, an object is created to represent a function - without an internal state and with a very small class (containing more or less all the code for implementing your function). Due to the limited use of this object, I would expect Hotspot to be able to use many optimizations here. Then an additional method will be added for the apply function compared to the match statement. Again, this is a fixed (and generic) template that, as I expect it, can be optimized quite a lot.
Essentially, any overhead would be negligible. As with all optimizations, it would be premature to write your code in an artificially short / less natural way until you determine that this is a performance bottleneck.
And if performance was really a critical issue, chances are you will end up being much more optimized than any option.
At the same time, relax and enjoy the βkindnessβ that first-class features will bring to you!
source share