gpt4 book ai didi

performance - 隐式值类中的继承是否会带来开销?

转载 作者:行者123 更新时间:2023-12-04 04:17:48 26 4
gpt4 key购买 nike

我想将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

}
}

我的问题:不管我何时使用 Ordered的继承关系,是否会强制分配 Pos对象(从而导致大量开销)?如果是这样:有办法避免这种情况吗?

最佳答案

每次将Pos视为Ordered[Pos],都会进行分配。
在某些情况下必须进行分配,请参见http://docs.scala-lang.org/overviews/core/value-classes.html#when_allocation_is_necessary

因此,当做像调用<这样的简单操作时,您将获得分配:

val x = Pos( 1 )
val y = Pos( 2 )
x < y // x & y promoted to an actual instance (allocation)

相关规则如下(引自以上文章):

Whenever a value class is treated as another type, including a universal trait, an instance of the actual value class must be instantiated and: Another instance of this rule is when a value class is used as a type argument.



分解上面的代码片段可以确认这一点:
 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

可以看出,对于类 Position$Pos,我们确实有两个"new"操作码实例

UPDATE :为了避免在这种简单情况下进行分配,您可以手动覆盖每个方法(即使它们仅转发给原始实现):
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)

例如,这将在执行 x < y时删除分配。
但是,仍然保留 Pos被视为 Ordered[Pos]的情况(就像传递给采用 Ordered[Pos]Ordered[T]且T为类型参数的方法时一样)。在这种情况下,您仍然会获得分配,而且没有办法解决。

关于performance - 隐式值类中的继承是否会带来开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16539503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com