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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With