Skip to content

Commit

Permalink
Merge pull request #9681 from sirthias/master
Browse files Browse the repository at this point in the history
[Library] Remove allocation overhead in Iterator#collect
  • Loading branch information
lrytz committed Jun 30, 2021
2 parents 7d79bbd + e987b5a commit f611f6c
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/library/scala/collection/Iterator.scala
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ trait Iterator[+A] extends IterableOnce[A] with IterableOnceOps[A, Iterator, Ite
*/
def withFilter(p: A => Boolean): Iterator[A] = filter(p)

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

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

def apply(value: A): B = Statics.pfMarker.asInstanceOf[B]

def hasNext = {
val marker = Statics.pfMarker
while (status == 0/*Seek*/) {
if (self.hasNext) {
val x = self.next()
val v = pf.applyOrElse(x, ((x: A) => marker).asInstanceOf[A => B])
val v = pf.applyOrElse(x, this)
if (marker ne v.asInstanceOf[AnyRef]) {
hd = v
status = 1/*Found*/
Expand Down

0 comments on commit f611f6c

Please sign in to comment.