Scala - the overhead of calling "first class functions"

First of all, please do not hesitate to correct the title of my question, I am not too familiar with the functional programming of lingo.

My question is whether there is any overhead (and how important this is) for treating functions as "variable contents". For example, in the following code:

class Processor { val map = Map[Class[_],AnyRef => Something](...) def process(c:AnyRef):Something = map(c.getClass)(c) def worksFor:List[Class[_]] = map.map(_._1) } 

really nice compared to:

 class Processor { def worksFor = List(classOf[Bears], classOf[Beets], classOf[BattlestarGalactica]) def process(c: AnyRef) = { c match { case c: Bears .... . . . } } } 

but will it be worse? (Obviously, the card will require more memory)

Thanks for any answer!

+6
source share
1 answer

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!

+11
source

Source: https://habr.com/ru/post/895413/


All Articles