gpt4 book ai didi

scala - 为什么 Scala 在解包 Tuple 时要构造一个新的 Tuple?

转载 作者:行者123 更新时间:2023-12-01 22:34:11 27 4
gpt4 key购买 nike

为什么这段 Scala 代码是这样的:

class Test
{
def foo: (Int, String) =
{
(123, "123")
}

def bar: Unit =
{
val (i, s) = foo
}
}

bar()生成以下字节码,构造一个新的Tuple2,并从foo()传递Tuple2 code> 到它然后从中获取值?

public void bar();
Code:
0: aload_0
1: invokevirtual #28; //Method foo:()Lscala/Tuple2;
4: astore_2
5: aload_2
6: ifnull 40
9: new #7; //class scala/Tuple2
12: dup
13: aload_2
14: invokevirtual #32; //Method scala/Tuple2._1:()Ljava/lang/Object;
17: aload_2
18: invokevirtual #35; //Method scala/Tuple2._2:()Ljava/lang/Object;
21: invokespecial #20; //Method scala/Tuple2."<init>":(Ljava/lang/Object;Ljava/lang/Object;)V
24: astore_1
25: aload_1
26: invokevirtual #39; //Method scala/Tuple2._1$mcI$sp:()I
29: istore_3
30: aload_1
31: invokevirtual #35; //Method scala/Tuple2._2:()Ljava/lang/Object;
34: checkcast #41; //class java/lang/String
37: astore 4

这是因为编译器没有检查 foo() 的返回值不是元组吗?

JVM 会优化构造吗?

最佳答案

这似乎是根据spec (在 4.1 值声明和定义中 - 为 stackoverflow 显示稍微重新格式化):

Value definitions can alternatively have a pattern (§8.1) as left-hand side. If p is some pattern other than a simple name or a name followed by a colon and a type, then the value definition val p = e is expanded as follows:

  1. If the pattern p has bound variables x1, . . . , xn, where n >= 1: Here, $x is a fresh name.
  val $x = e match {case p => (x1, . . . , xn)}
val x1 = $x._1
. . .
val xn = $x._n

因此元组创建发生在解析器阶段。因此 val (i, s) = (1, "s") 在解析器阶段结束时消耗为:

private[this] val x$1 = scala.Tuple2(1, "s"): @scala.unchecked match {    
case scala.Tuple2((i @ _), (s @ _)) => scala.Tuple2(i, s)
};
val i = x$1._1;
val s = x$1._2

通过一百万次迭代的简单测试来测量这一点:

def foo: (Int, String) = (123, "123")
def bar: Unit = { val (i, s) = foo }
def bam: Unit = { val f = foo; val i = f._1; val s = f._2 }

产量

foo: Elapsed: 0.030
bar: Elapsed: 0.051
._1 ._2 access: Elapsed: 0.040

并带有 -optimize 标志:

foo: Elapsed: 0.027
bar: Elapsed: 0.049
._1 ._2 access: Elapsed: 0.029

关于scala - 为什么 Scala 在解包 Tuple 时要构造一个新的 Tuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8192620/

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