When should I (and should I not) use Scala's @inline annotation?

我只是一个虾纸丫 提交于 2019-12-29 18:45:24

问题


I believe I understand the basics of inline functions: instead of a function call resulting in parameters being placed on the stack and an invoke operation occurring, the definition of the function is copied at compile time to where the invocation was made, saving the invocation overhead at runtime.

So I want to know:

  • Does scalac use smarts to inline some functions (e.g. private def) without the hints from annotations?

  • How do I judge when it be a good idea to hint to scalac that it inlines a function?

  • Can anyone share examples of functions or invocations that should or shouldn't be inlined?


回答1:


Never @inline anything whose implementation might reasonably change and which is going to be a public part of a library.

When I say "implementation change" I mean that the logic actually might change. For example:

object TradeComparator extends java.lang.Comparator[Trade] {
  @inline def compare(t1 : Trade, t2 : Trade) Int = t1.time compare t2.time
}

Let's say the "natural comparison" then changed to be based on an atomic counter. You may find that an application ends up with 2 components, each built and inlined against different versions of the comparison code.




回答2:


Personally, I use @inline for alias:

class A(param: Param){
  @inline def a = param.a
  def a2() = a * a
}

Now, I couldn't find a way to know if it does anything (I tried to jad the generated .class, but couldn't conclude anything).

My goal is to explicit what I want the compiler to do. But let it decide what's best, or simply do what it's capable of. If it doesn't do it, maybe later compiler version will.



来源:https://stackoverflow.com/questions/4593710/when-should-i-and-should-i-not-use-scalas-inline-annotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!