Skip to content

Commit c8fe7c8

Browse files
authored
Merge pull request scala#7115 from viktorklang/wip-reuse-empty-iterator-vector-√
Changing s.c.i.Vector.iterator to return Iterator.empty on empty
2 parents 98a68df + 7eed53a commit c8fe7c8

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/library/scala/collection/immutable/Vector.scala

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,14 @@ final class Vector[+A] private[immutable] (private[collection] val startIndex: I
8686
if (s.depth > 1) s.gotoPos(startIndex, startIndex ^ focus)
8787
}
8888

89-
override def iterator: VectorIterator[A] = {
90-
val s = new VectorIterator[A](startIndex, endIndex)
91-
initIterator(s)
92-
s
89+
override def iterator: Iterator[A] = {
90+
if(isEmpty)
91+
Iterator.empty
92+
else {
93+
val s = new VectorIterator[A](startIndex, endIndex)
94+
initIterator(s)
95+
s
96+
}
9397
}
9498

9599
// Ideally, clients will inline calls to map all the way down, including the iterator/builder methods.

test/junit/scala/collection/immutable/VectorTest.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,10 @@ class VectorTest {
5050
}
5151

5252
@Test def checkSearch: Unit = SeqTests.checkSearch(Vector(0 to 1000: _*), 15, implicitly[Ordering[Int]])
53+
54+
@Test
55+
def emptyIteratorReuse(): Unit = {
56+
assertSame(Vector.empty.iterator, Vector.empty.iterator)
57+
assertSame(Vector.empty.iterator, Vector(1).drop(1).iterator)
58+
}
5359
}

0 commit comments

Comments
 (0)