Skip to content

Commit 9012222

Browse files
committed
use fast intersect and diff where we can
1 parent c003048 commit 9012222

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

library/src/scala/collection/generic/Subtractable.scala

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ package scala
1414
package collection
1515
package generic
1616

17+
import scala.collection.immutable.HashSet
18+
1719

1820
/** This trait represents collection-like objects that can be reduced
1921
* using a '+' operator. It defines variants of `-` and `--`
@@ -59,5 +61,10 @@ trait Subtractable[A, +Repr <: Subtractable[A, Repr]] { self =>
5961
* @return a new $coll that contains all elements of the current $coll
6062
* except one less occurrence of each of the elements of `elems`.
6163
*/
62-
def --(xs: GenTraversableOnce[A]): Repr = (repr /: xs.seq) (_ - _)
64+
def --(xs: GenTraversableOnce[A]): Repr = this match {
65+
case hs: HashSet[A] if xs.isInstanceOf[HashSet[A]] =>
66+
hs.diff(xs.asInstanceOf[HashSet[A]]).asInstanceOf[Repr]
67+
case _ =>
68+
(repr /: xs.seq) (_ - _)
69+
}
6370
}

library/src/scala/collection/immutable/HashSet.scala

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -166,16 +166,24 @@ sealed class HashSet[A] extends AbstractSet[A]
166166

167167
override def tail: HashSet[A] = this - head
168168

169-
override def filter(p: A => Boolean) = {
170-
val buffer = new Array[HashSet[A]](bufferSize(size))
171-
nullToEmpty(filter0(p, false, 0, buffer, 0))
169+
override def filter(p: A => Boolean) = p match {
170+
case hs: HashSet[A] =>
171+
intersect(hs)
172+
case _ =>
173+
val buffer = new Array[HashSet[A]](bufferSize(size))
174+
nullToEmpty(filter0(p, false, 0, buffer, 0))
172175
}
173176

174-
override def filterNot(p: A => Boolean) = {
175-
val buffer = new Array[HashSet[A]](bufferSize(size))
176-
nullToEmpty(filter0(p, true, 0, buffer, 0))
177+
override def filterNot(p: A => Boolean) = p match {
178+
case hs: HashSet[A] =>
179+
diff(hs)
180+
case _ =>
181+
val buffer = new Array[HashSet[A]](bufferSize(size))
182+
nullToEmpty(filter0(p, true, 0, buffer, 0))
177183
}
178184

185+
186+
179187
protected def filter0(p: A => Boolean, negate: Boolean, level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = null
180188

181189
protected def elemHashCode(key: A) = key.##

0 commit comments

Comments
 (0)