Scala 中的@inline 注释真的有助于提高性能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2709095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does the @inline annotation in Scala really help performance?
提问by Alex R
Or does it just clutter up the code for something the JIT would take care of automatically anyway?
或者它是否只是将 JIT 会自动处理的代码弄得乱七八糟?
采纳答案by Rex Kerr
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).
我还没有找到可以提高性能的案例,而且我已经在很多不同的地方进行了尝试。JVM 似乎在可能的情况下非常擅长内联,即使你在 Scala 中要求 @inline,它也不能总是这样做(有时我注意到它甚至在我认为它应该能够)。
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.
当用-optimise. 您确实看到了差异,但它通常不会运行得更快,因为 JIT 编译器可以注意到相同的优化适用于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.
所以在优化的最后阶段可能值得一试,但我不会在不检查它是否对性能产生影响的情况下进行常规操作。

