Does the @inline annotation in Scala really help performance?
Asked Answered
J

1

65

Or does it just clutter up the code for something the JIT would take care of automatically anyway?

Justus answered 25/4, 2010 at 17:11 Comment(0)
P
60

I have yet to find a case where it improves performance, and I've tried in quite a few different spots. The JVM seems to be quite good at inlining when it's possible, and even if you ask for @inline in Scala, it can't always do it (and sometimes I've noticed that it doesn't even when I think it ought to be able to).

The place where you expect to see a bytecode difference is in something like this:

object InlineExample {
  final class C(val i: Int) {
    @inline def t2 = i*2
    @inline def t4 = t2*2
  }
  final class D(val i: Int) {
    def t2 = i*2
    def t4 = t2*2
  }
}

when compiled with -optimise. And you do see the difference, but it generally doesn't run any faster since the JIT compiler can notice that the same optimizations apply to D.

So it may be worth a try in the final stages of optimization, but I wouldn't bother doing it routinely without checking to see if it makes a difference in performance.

Peculium answered 25/4, 2010 at 21:44 Comment(9)
Thanks for reporting your test results; saved me and probably others some time :)Justus
You argument is only true if there was only one JIT compiler on the planet. — But this is not true. There is Android, there is IBM which produces there own JVMs. So anything the Scala compiler does for sure is better then something some JIT might do.Pork
@Pork - I admit that haven't tried Android. I've tried JRockit and the IBM JVM with the same effect as the Sun JVM (i.e. none).Peculium
I still have a question open. Does the @inline at least tell me that a method can reliably be inlined from the jit? So that i can use it to get compile time informations of runtime optimizations. And what about non HotSpot Jvm? How does it perform on Android.Ocko
@Ocko - Inline tells the Scala compiler to try to inline the method. It doesn't know what the JVM may or may not do. Dalvik inlines getters/setters but not much else as I understand it, so it's worth testing for improvements with inline there.Peculium
I've had some luck recently using inline. ~15% performance increase for a heavily used function.Babette
2.10.2 -- I realize this is an old answer, but I figured I would comment.Babette
@WesFreeman, based on this experience how would you describe a (potentially) effective use of inline?Linette
In Kotlin inlining also exists. It is also used for things beyong performance improvements such as implementing non-local returns, see kotlinlang.org/docs/reference/inline-functions.html That non-local returns are discontinued in Scala 3 is something that really bothers me. It could be implemented in Scala 3 as well just as in Kotlin.Farceur

© 2022 - 2024 — McMap. All rights reserved.