diff options
author | Jason Zaugg <jzaugg@gmail.com> | 2012-09-29 18:15:15 +0200 |
---|---|---|
committer | Jason Zaugg <jzaugg@gmail.com> | 2012-11-04 21:21:51 +0100 |
commit | bc3dda2b0222d3b7cf3db491728b98f9b6110856 (patch) | |
tree | d71d81b7c443e75e12da82e9d6e8c53c84d31f1d /src/library/scala/collection/TraversableOnce.scala | |
parent | 2c6777fd53b93b95a261aadc87a5cbc03c14d503 (diff) | |
download | scala-bc3dda2b0222d3b7cf3db491728b98f9b6110856.tar.gz scala-bc3dda2b0222d3b7cf3db491728b98f9b6110856.tar.bz2 scala-bc3dda2b0222d3b7cf3db491728b98f9b6110856.zip |
SI-6448 Collecting the spoils of PartialFun#runWith
Avoids calling both `isDefinedAt` and `apply`. This pathological
case that would benefit the most looks like:
xs collect {
case x if {expensive(); true} => x
}
The typical change looks like:
- for (x <- this) if (pf.isDefinedAt(x)) b += pf(x)
+ foreach(pf.runWith(b += _))
Incorporates feedback provided by Pavel Pavlov:
https://github.com/retronym/scala/commit/ef5430
A few more opportunities for optimization are noted in the
`Pending` section of the enclosed test. `Iterator.collect`
would be nice, but a solution eludes me.
Calling the guard less frequently does change the behaviour
of these functions in an obervable way, but not contravene
the documented semantics. That said, there is an alternative
opinion on the comment of the ticket:
https://issues.scala-lang.org/browse/SI-6448
Diffstat (limited to 'src/library/scala/collection/TraversableOnce.scala')
-rw-r--r-- | src/library/scala/collection/TraversableOnce.scala | 6 |
1 files changed, 2 insertions, 4 deletions
diff --git a/src/library/scala/collection/TraversableOnce.scala b/src/library/scala/collection/TraversableOnce.scala index a61d1354dc..569412a441 100644 --- a/src/library/scala/collection/TraversableOnce.scala +++ b/src/library/scala/collection/TraversableOnce.scala @@ -128,10 +128,8 @@ trait TraversableOnce[+A] extends Any with GenTraversableOnce[A] { * @example `Seq("a", 1, 5L).collectFirst({ case x: Int => x*10 }) = Some(10)` */ def collectFirst[B](pf: PartialFunction[A, B]): Option[B] = { - for (x <- self.toIterator) { // make sure to use an iterator or `seq` - if (pf isDefinedAt x) - return Some(pf(x)) - } + // make sure to use an iterator or `seq` + self.toIterator.foreach(pf.runWith(b => return Some(b))) None } |