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 distinctBy implementation for non-empty collections #4711

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

BartekBH
Copy link

Addresses #4610

}

NonEmptyList(head, buf.toList)
NonEmptyList.fromListUnsafe(bldr.result())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be slightly better to do:

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())

the main changes:

  1. we don't have to build an iterator for the list, we just directly iterate on List
  2. we don't have to allocate the outermost List just to destructure it inside NonEmptyList.fromListUnsafe.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd also suggest to check if the source NeList has 1 item only (tail.isEmpty or use sizeCompare) and simply return this in that case.
It would help to avoid allocating unnecessary structures: the builder and tree set and recreating 1-item NeList.

This small optimization could also be applied to the other two collections.

}

NonEmptySeq(head, buf.result())
NonEmptySeq.fromSeqUnsafe(bldr.result())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this one is different from NonEmptyList, because it is a wrapper on the whole Seq, unlike NonEmptyList which is a class.

Given that, this implementation here seems good to me.

@BartekBH
Copy link
Author

BartekBH commented Feb 1, 2025

Thanks, I’ve implemented your comments. Hope it's good now.

@@ -345,16 +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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually this could be moved inside the else branch to avoid it on singletons.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants