Skip to content

Commit 96b9397

Browse files
authored
Merge pull request scala/scala#10248 from som-snytt/tweak/12316
Minor refactor in ListSet to foreground guards and add test
2 parents 64789bd + d544bb3 commit 96b9397

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

library/src/scala/collection/immutable/ListSet.scala

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -82,18 +82,15 @@ sealed class ListSet[A] extends AbstractSet[A]
8282

8383
override def ++(xs: GenTraversableOnce[A]): ListSet[A] =
8484
xs match {
85-
// we want to avoid to use of iterator as it causes allocations
86-
// during reverseList
87-
case ls: ListSet[A] =>
88-
if (ls eq this) this
89-
else {
90-
val lsSize = ls.size
91-
if (lsSize == 0) this
92-
else if (isEmpty) ls
85+
case _: this.type => this
86+
case _ if xs.isEmpty => this
87+
// we want to avoid using iterator as it causes allocations during reverseList
88+
case ls: ListSet[A] =>
89+
if (isEmpty) ls
9390
else {
94-
@tailrec def skip(ls: ListSet[A], count: Int): ListSet[A] = {
91+
// optimize add non-empty ListSet
92+
@tailrec def skip(ls: ListSet[A], count: Int): ListSet[A] =
9593
if (count == 0) ls else skip(ls.next, count - 1)
96-
}
9794

9895
@tailrec def containsLimited(n: ListSet[A], e: A, end: ListSet[A]): Boolean =
9996
(n ne end) && (e == n.elem || containsLimited(n.next, e, end))
@@ -104,6 +101,7 @@ sealed class ListSet[A] extends AbstractSet[A]
104101
// We hope to get some structural sharing so find the tail of the
105102
// ListSet that are `eq` (or if there are not any then the ends of the lists),
106103
// and we optimise the add to only iterate until we reach the common end
104+
val lsSize = ls.size
107105
val thisSize = this.size
108106
val remaining = Math.min(thisSize, lsSize)
109107
var thisTail = skip(this, thisSize - remaining)
@@ -151,16 +149,13 @@ sealed class ListSet[A] extends AbstractSet[A]
151149
case 4 => pending3
152150
case _ => pending(pendingCount - 5)
153151
}
154-
val r = result
152+
val r = result
155153
result = new r.Node(elem)
156154
pendingCount -= 1
157155
}
158156
result
159157
}
160-
}
161-
case _ =>
162-
if (xs.isEmpty) this
163-
else (repr /: xs) (_ + _)
158+
case _ => xs.foldLeft(repr)(_ + _)
164159
}
165160

166161
def iterator: Iterator[A] = {

0 commit comments

Comments
 (0)