Skip to content

Commit

Permalink
Improve optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
Bartek committed Feb 1, 2025
1 parent 572fbfa commit 44b076d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 24 deletions.
23 changes: 15 additions & 8 deletions core/src/main/scala/cats/data/NonEmptyList.scala
Original file line number Diff line number Diff line change
Expand Up @@ -345,15 +345,22 @@ final case class NonEmptyList[+A](head: A, tail: List[A]) extends NonEmptyCollec
override def distinctBy[B](f: A => B)(implicit O: Order[B]): NonEmptyList[A] = {
implicit val ord: Ordering[B] = O.toOrdering

val bldr = List.newBuilder[A]
val seen = mutable.TreeSet.empty[B]
val it = iterator
while (it.hasNext) {
val next = it.next()
if (seen.add(f(next)))
bldr += next
if (tail.isEmpty) this
else {
val bldr = List.newBuilder[A]
val seen = mutable.TreeSet.empty[B]
var rest = tail
seen.add(f(head))
while (rest.nonEmpty) {
val next = rest.head
rest = rest.tail
if (seen.add(f(next))) {
bldr += next
}
}

NonEmptyList(head, bldr.result())
}
NonEmptyList.fromListUnsafe(bldr.result())
}

/**
Expand Down
20 changes: 12 additions & 8 deletions core/src/main/scala/cats/data/NonEmptySeq.scala
Original file line number Diff line number Diff line change
Expand Up @@ -241,15 +241,19 @@ final class NonEmptySeq[+A] private (val toSeq: Seq[A]) extends AnyVal with NonE
override def distinctBy[B](f: A => B)(implicit O: Order[B]): NonEmptySeq[A] = {
implicit val ord: Ordering[B] = O.toOrdering

val bldr = Seq.newBuilder[A]
val seen = mutable.TreeSet.empty[B]
val it = iterator
while (it.hasNext) {
val next = it.next()
if (seen.add(f(next)))
bldr += next
if (toSeq.sizeIs == 1) this
else {
val bldr = Seq.newBuilder[A]
val seen = mutable.TreeSet.empty[B]
val it = iterator
while (it.hasNext) {
val next = it.next()
if (seen.add(f(next)))
bldr += next
}

NonEmptySeq.fromSeqUnsafe(bldr.result())
}
NonEmptySeq.fromSeqUnsafe(bldr.result())
}

/**
Expand Down
20 changes: 12 additions & 8 deletions core/src/main/scala/cats/data/NonEmptyVector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -251,15 +251,19 @@ final class NonEmptyVector[+A] private (val toVector: Vector[A])
override def distinctBy[B](f: A => B)(implicit O: Order[B]): NonEmptyVector[A] = {
implicit val ord: Ordering[B] = O.toOrdering

val bldr = Vector.newBuilder[A]
val seen = mutable.TreeSet.empty[B]
val it = iterator
while (it.hasNext) {
val next = it.next()
if (seen.add(f(next)))
bldr += next
if (toVector.sizeIs == 1) this
else {
val bldr = Vector.newBuilder[A]
val seen = mutable.TreeSet.empty[B]
val it = iterator
while (it.hasNext) {
val next = it.next()
if (seen.add(f(next)))
bldr += next
}

NonEmptyVector.fromVectorUnsafe(bldr.result())
}
NonEmptyVector.fromVectorUnsafe(bldr.result())
}

/**
Expand Down

0 comments on commit 44b076d

Please sign in to comment.