Skip to content

Commit e987b5a

Browse files
committed
[Library] Remove allocation overhead in Iterator#collect
1 parent 7d79bbd commit e987b5a

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/library/scala/collection/Iterator.scala

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -498,7 +498,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite
498498
*/
499499
def withFilter(p: A => Boolean): Iterator[A] = filter(p)
500500

501-
def collect[B](pf: PartialFunction[A, B]): Iterator[B] = new AbstractIterator[B] {
501+
def collect[B](pf: PartialFunction[A, B]): Iterator[B] = new AbstractIterator[B] with (A => B) {
502502
// Manually buffer to avoid extra layer of wrapping with buffered
503503
private[this] var hd: B = _
504504

@@ -508,12 +508,14 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite
508508
// BE REALLY CAREFUL TO KEEP COMMENTS AND NUMBERS IN SYNC!
509509
private[this] var status = 0/*Seek*/
510510

511+
def apply(value: A): B = Statics.pfMarker.asInstanceOf[B]
512+
511513
def hasNext = {
512514
val marker = Statics.pfMarker
513515
while (status == 0/*Seek*/) {
514516
if (self.hasNext) {
515517
val x = self.next()
516-
val v = pf.applyOrElse(x, ((x: A) => marker).asInstanceOf[A => B])
518+
val v = pf.applyOrElse(x, this)
517519
if (marker ne v.asInstanceOf[AnyRef]) {
518520
hd = v
519521
status = 1/*Found*/

0 commit comments

Comments
 (0)