Skip to content

Commit

Permalink
Merge pull request scala#8789 from mkeskells/2.12.x_SeqList1
Browse files Browse the repository at this point in the history
avoid creation of ListBuffers for Seq.empty and Seq()
  • Loading branch information
retronym authored Mar 24, 2020
2 parents 794b453 + b198815 commit bb4d3e2
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
5 changes: 4 additions & 1 deletion src/library/scala/collection/generic/GenericCompanion.scala
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ abstract class GenericCompanion[+CC[X] <: GenTraversable[X]] {
/** An empty collection of type `$Coll[A]`
* @tparam A the type of the ${coll}'s elements
*/
def empty[A]: CC[A] = newBuilder[A].result()
def empty[A]: CC[A] = {
if ((this eq immutable.Seq) || (this eq collection.Seq)) Nil.asInstanceOf[CC[A]]
else newBuilder[A].result()
}

/** Creates a $coll with the specified elements.
* @tparam A the type of the ${coll}'s elements
Expand Down
16 changes: 16 additions & 0 deletions test/junit/scala/collection/SeqTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package scala.collection

import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import scala.tools.testing.AllocationTest

@RunWith(classOf[JUnit4])
class SeqTest extends AllocationTest{

@Test def emptyNonAllocating(): Unit = {
nonAllocating(Seq.empty)
nonAllocating(Seq())
}
}
8 changes: 7 additions & 1 deletion test/junit/scala/collection/immutable/ListTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ import org.junit.runner.RunWith
import org.junit.runners.JUnit4

import scala.ref.WeakReference
import scala.tools.testing.AllocationTest

@RunWith(classOf[JUnit4])
class ListTest {
class ListTest extends AllocationTest{
/**
* Test that empty iterator does not hold reference
* to complete List
Expand Down Expand Up @@ -46,4 +47,9 @@ class ListTest {
// real assertion
Assert.assertTrue(emptyIterators.exists(_._2.get.isEmpty))
}

@Test def emptyNonAllocating(): Unit = {
nonAllocating(List.empty)
nonAllocating(List())
}
}
16 changes: 16 additions & 0 deletions test/junit/scala/collection/immutable/SeqTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package scala.collection.immutable

import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.junit.{Assert, Test}

import scala.tools.testing.AllocationTest

@RunWith(classOf[JUnit4])
class SeqTest extends AllocationTest{

@Test def emptyNonAllocating(): Unit = {
nonAllocating(Seq.empty)
nonAllocating(Seq())
}
}

0 comments on commit bb4d3e2

Please sign in to comment.