Skip to content

Commit bb4d3e2

Browse files
authored
Merge pull request scala#8789 from mkeskells/2.12.x_SeqList1
avoid creation of ListBuffers for Seq.empty and Seq()
2 parents 794b453 + b198815 commit bb4d3e2

File tree

4 files changed

+43
-2
lines changed

4 files changed

+43
-2
lines changed

src/library/scala/collection/generic/GenericCompanion.scala

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ abstract class GenericCompanion[+CC[X] <: GenTraversable[X]] {
3939
/** An empty collection of type `$Coll[A]`
4040
* @tparam A the type of the ${coll}'s elements
4141
*/
42-
def empty[A]: CC[A] = newBuilder[A].result()
42+
def empty[A]: CC[A] = {
43+
if ((this eq immutable.Seq) || (this eq collection.Seq)) Nil.asInstanceOf[CC[A]]
44+
else newBuilder[A].result()
45+
}
4346

4447
/** Creates a $coll with the specified elements.
4548
* @tparam A the type of the ${coll}'s elements
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package scala.collection
2+
3+
import org.junit.Test
4+
import org.junit.runner.RunWith
5+
import org.junit.runners.JUnit4
6+
7+
import scala.tools.testing.AllocationTest
8+
9+
@RunWith(classOf[JUnit4])
10+
class SeqTest extends AllocationTest{
11+
12+
@Test def emptyNonAllocating(): Unit = {
13+
nonAllocating(Seq.empty)
14+
nonAllocating(Seq())
15+
}
16+
}

test/junit/scala/collection/immutable/ListTest.scala

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ import org.junit.runner.RunWith
55
import org.junit.runners.JUnit4
66

77
import scala.ref.WeakReference
8+
import scala.tools.testing.AllocationTest
89

910
@RunWith(classOf[JUnit4])
10-
class ListTest {
11+
class ListTest extends AllocationTest{
1112
/**
1213
* Test that empty iterator does not hold reference
1314
* to complete List
@@ -46,4 +47,9 @@ class ListTest {
4647
// real assertion
4748
Assert.assertTrue(emptyIterators.exists(_._2.get.isEmpty))
4849
}
50+
51+
@Test def emptyNonAllocating(): Unit = {
52+
nonAllocating(List.empty)
53+
nonAllocating(List())
54+
}
4955
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package scala.collection.immutable
2+
3+
import org.junit.runner.RunWith
4+
import org.junit.runners.JUnit4
5+
import org.junit.{Assert, Test}
6+
7+
import scala.tools.testing.AllocationTest
8+
9+
@RunWith(classOf[JUnit4])
10+
class SeqTest extends AllocationTest{
11+
12+
@Test def emptyNonAllocating(): Unit = {
13+
nonAllocating(Seq.empty)
14+
nonAllocating(Seq())
15+
}
16+
}

0 commit comments

Comments
 (0)