Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - overhead of invoking 'first class functions'

First of all, please feel free to correct the title of my question, i'm not too familiar with functional-programming lingo.

My question is, is there any overhead (and how significant it is) of treating functions as 'content of variables'. For example in 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)
}

is 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 perform any worse? (Obviously it will take more memory, because of the map)

Thanks for any kind of answer!

like image 889
Arg Avatar asked Aug 19 '11 11:08

Arg


1 Answers

When you assign a function as a value, the object created is an instance of one of the Function classes (Function1 if it takes a single argument, Function2 if it takes two arguments, etc.). Actually invoking the function is just a matter of calling the apply method on the FunctionN object.

In that respect, there's really very little overhead unless you're looking at a critical loop. Theoretically, an object is created to represent the function - one with no internal state, and of a very small class (containing, more or less, just the code to implement your function). Due to the limited manner in which this object is used, I'd expect Hotspot to be able to apply a lot of optimisations here though. Then there will be an additional method dispatch to the function's apply method, compared with the match statement. Again this is a fixed (and common) pattern such that I expect it can be optimised quite a lot.


Essentially, any overhead will be negligible. As with all optimisations, it would be premature to write your code in an artificially terse/less natural way until you've identified that it's a performance bottleneck.

And if performance really was a critical problem here, chances are you'd end up going for something a lot more optimised than either option.

In the meantime, relax and enjoy the "niceness" that first-class functions give you!

like image 118
Andrzej Doyle Avatar answered Nov 15 '22 06:11

Andrzej Doyle