diff --git a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala index 98ca8f2e2b5b..1a6ec307e289 100644 --- a/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala +++ b/compiler/src/dotty/tools/dotc/transform/ArrayApply.scala @@ -76,7 +76,7 @@ class ArrayApply extends MiniPhase { tree.args match // (a, b, c) ~> new ::(a, new ::(b, new ::(c, Nil))) but only for reference types case StripAscription(Apply(wrapArrayMeth, List(StripAscription(rest: JavaSeqLiteral)))) :: Nil - if defn.WrapArrayMethods().contains(wrapArrayMeth.symbol) => + if rest.elems.isEmpty || defn.WrapArrayMethods().contains(wrapArrayMeth.symbol) => Some(rest.elems) case _ => None else None diff --git a/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala b/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala index c99de8fcf956..a1fe40e58b56 100644 --- a/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala +++ b/compiler/test/dotty/tools/backend/jvm/ArrayApplyOptTest.scala @@ -161,6 +161,42 @@ class ArrayApplyOptTest extends DottyBytecodeTest { } } + @Test def emptyListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("EmptyList"): + """import scala.collection.immutable.Nil + |class Foo { + | def meth1: List[String] = List() + | def meth2: List[String] = Nil + |} + """.stripMargin + + @Test def emptyRefListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("EmptyListOfRef"): + """import scala.collection.immutable.Nil + |class Foo { + | def meth1: List[String] = List[String]() + | def meth2: List[String] = Nil + |} + """.stripMargin + + @Test def emptyPrimitiveListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("EmptyListOfInt"): + """import scala.collection.immutable.Nil + |class Foo { + | def meth1: List[Int] = List() + | def meth2: List[Int] = Nil + |} + """.stripMargin + + @Test def primitiveListApplyAvoidsIntermediateArray = + checkApplyAvoidsIntermediateArray("ListOfInt"): + """import scala.collection.immutable.{ ::, Nil } + |class Foo { + | def meth1: List[Int] = List(1, 2, 3) + | def meth2: List[Int] = new ::(1, new ::(2, new ::(3, Nil))) + |} + """.stripMargin + @Test def testListApplyAvoidsIntermediateArray = { checkApplyAvoidsIntermediateArray("List"): """import scala.collection.immutable.{ ::, Nil }