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

后端 未结 2 831
一向
一向 2020-12-24 11:14

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 de

相关标签:
2条回答
  • 2020-12-24 11:58

    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.

    0 讨论(0)
  • 2020-12-24 11:59

    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.

    0 讨论(0)
提交回复
热议问题