Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize distinct/distinctBy implementations for non-empty collections #4610

Open
satorg opened this issue Jun 5, 2024 · 0 comments
Open
Labels
good first issue Issues that are easier to take on for first time contributors optimization

Comments

@satorg
Copy link
Contributor

satorg commented Jun 5, 2024

A follow up for #4608 (see my comment #4608 (comment)).
For an example of a pretty well optimized implementation one could check out the corresponding methods in Chain:

def distinct[AA >: A](implicit O: Order[AA]): Chain[AA] = {
if (isEmptyOrSingleton) this
else {
implicit val ord: Ordering[AA] = O.toOrdering
val bldr = Vector.newBuilder[AA]
val seen = mutable.TreeSet.empty[AA]
val it = iterator
while (it.hasNext) {
val next = it.next()
if (seen.add(next))
bldr += next
}
// Result can contain a single element only.
Chain.fromSeq(bldr.result())
}
}

def distinctBy[B](f: A => B)(implicit O: Order[B]): Chain[A] = {
if (isEmptyOrSingleton) this
else {
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
}
// Result can contain a single element only.
Chain.fromSeq(bldr.result())
}
}

@satorg satorg added good first issue Issues that are easier to take on for first time contributors optimization labels Jun 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Issues that are easier to take on for first time contributors optimization
Projects
None yet
Development

No branches or pull requests

1 participant