Performance 隐式值类中的继承会引入开销吗?

Performance 隐式值类中的继承会引入开销吗?,performance,scala,implicit,value-class,Performance,Scala,Implicit,Value Class,我想将scala的值类应用到我的一个项目中,因为它们使我能够在不产生太大开销的情况下(我希望如此)丰富某些基本类型,并保持类型安全 object Position { implicit class Pos( val i: Int ) extends AnyVal with Ordered[Pos] { def +( p: Pos ): Pos = i + p.i def -( p: Pos ): Pos = if ( i - p.i < 0 ) 0 else i

我想将scala的值类应用到我的一个项目中,因为它们使我能够在不产生太大开销的情况下(我希望如此)丰富某些基本类型,并保持类型安全

object Position {

  implicit class Pos( val i: Int ) extends AnyVal with Ordered[Pos] {

    def +( p: Pos ): Pos = i + p.i

    def -( p: Pos ): Pos = if ( i - p.i < 0 ) 0 else i - p.i

    def compare( p: Pos ): Int = i - p.i

  }
}
对象位置{
隐式类Pos(val i:Int)用Ordered[Pos]扩展AnyVal{
def+(p:Pos):Pos=i+p.i
def-(p:Pos):Pos=if(i-p.i<0)0其他i-p.i
def比较(p:Pos):Int=i-p.i
}
}

我的问题:无论何时我使用
Pos
对象,有序
的继承是否会强制分配它们(从而带来巨大的开销)?如果是这样的话:有没有办法避免这种情况?

每次
Pos
都会被视为
订购的[Pos]
,分配就会发生。 有几种情况下必须进行分配,请参阅


所以,当你做一些像调用
这样简单的事情时,你知道有什么方法可以避免分配,从而使Pos具有可比性吗?
val x = Pos( 1 )
val y = Pos( 2 )
x < y // x & y promoted to an actual instance (allocation)
 0: aload_0
 1: iconst_1
 2: invokevirtual #21                 // Method Pos:(I)I
 5: istore_1
 6: aload_0
 7: iconst_2
 8: invokevirtual #21                 // Method Pos:(I)I
11: istore_2
12: new           #23                 // class test/Position$Pos
15: dup
16: iload_1
17: invokespecial #26                 // Method test/Position$Pos."<init>":(I)V
20: new           #23                 // class test/Position$Pos
23: dup
24: iload_2
25: invokespecial #26                 // Method test/Position$Pos."<init>":(I)V
28: invokeinterface #32,  2           // InterfaceMethod scala/math/Ordered.$less:(Ljava/lang/Object;)Z
override def <  (that: Pos): Boolean = super.<(that)
override def >  (that: Pos): Boolean = super.>(that)
override def <= (that: Pos): Boolean = super.<=(that)
override def >= (that: Pos): Boolean = super.>=(that)