Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scala (or the JVM) ever optimize (Function) objects away?

Tags:

jvm

scala

In a lot of cases with Scala, such as simple, locally-scoped function invocations, one can imagine that it would often be theoretically possible get rid of the function object altogether. But AFAIK, the JVM doesn't know how to do this, and I don't think Scala does either. Correct?

Are anonymous function objects always sealed? If not, there's a pretty hard limit on how much inlining can be done. Correct?

Is anyone aware of any planned efforts that are likely to address these kinds of optimizations?

See also the related pure-Java question: Does a modern JVM optimize simple inline anonymous class allocation?

(Chanting of "don't optimize too early", "it doesn't matter", et al is very redundant at this point and not useful.)

like image 431
Ed Staub Avatar asked Feb 25 '12 04:02

Ed Staub


Video Answer


1 Answers

Inlining plus escape analysis can do exactly that. You can demonstrate this to yourself if you use the compilation reporting in JVM 7, or benchmark the following two snippets of code:

def rfor(i0: Int, i1: Int)(f: Int => Unit) {
  var i = i0
  while (i <= i1) {
    f(i)
    i += 1
  }
}

def whiley = {
  var s = 0
  var n = 1
  while (n <= 500000000) {
    val k = n >> 2
    var i = 1
    while (i <= 2) {
      s += i*k
      i += 1
    }
    n += 1
  }
  s
}

def rfory = {
  var s = 0
  var n = 0
  while (n <= 500000000) {
    val k = n >> 2
    rfor(1, 2){ s += k * _ }
    n += 1
  }
  s
}

On my machine, the second one is at least as fast as the first one (sometimes faster), despite the second one seeming to require a function creation every other iteration.

like image 71
Rex Kerr Avatar answered Sep 23 '22 15:09

Rex Kerr