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 · 3 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
@sinpat
Copy link

sinpat commented Oct 20, 2024

Hi,
I would like to implement this optimization.
I haven't contributed yet and I think this could be a good first issue.

@BartekBH
Copy link

BartekBH commented Jan 30, 2025

Hi,

@sinpat Are you still working on this issue?

@satorg I took a look at it, and I believe I can implement this optimization. However, I want to clarify what exactly needs to be done. Based on your comments, is the optimization required only for NonEmptyList, NonEmptySeq, and NonEmptyVector? Am I correct? Also, should I provide some proof that the optimization is effective?

@sinpat
Copy link

sinpat commented Jan 31, 2025

Hi @BartekBH
feel free to go ahead.
I have been slacking horribly on this.

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

3 participants