Search code examples
scalascala-compiler

Will the compiler optimise calls to instance methods into static ones where it can?


Lets say I have something like:

case class StringList(list: List[String]) {

  final def isEmpty(): Boolean = list.isEmpty

}

Theoretically, the Scala compiler could optimise calls to the method isEmpty() and make them static...so that I don't have to write this:

object StringList {

  implicit class StringListExtensions(val strList: StringList) extends AnyVal {
    def isEmpty(): Boolean = strList.list.isEmpty
  }

}

or this:

object StringList {

  def isEmpty(strList: StringList): Boolean = strList.list.isEmpty

}

Solution

  • The answer is that the compiler probably won't do this because there is no real optimisation to be had.

    The list of methods for an object are held in a separate table that is shared between all instances of the object, so removing one method from that table makes very little difference to memory usage.

    The "static" version might make the call a bit more efficient because it does not need to indirect through this function table, but it is not certain that a JIT compiler will generate more efficient code in this case.

    So, as always, you should write the code that best expresses the effect you want to achieve, and only worry about performance when you have empirical evidence that this will make a real difference to your solution. And when you optimise, get the algorithms right before worrying about detailed language issues.