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

perf: Optimize the performance of union method, avoid repeated expansion #397

Merged
merged 1 commit into from
Jun 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions intersect.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,14 @@ func Difference[T comparable](list1 []T, list2 []T) ([]T, []T) {
// Union returns all distinct elements from given collections.
// result returns will not change the order of elements relatively.
func Union[T comparable](lists ...[]T) []T {
result := []T{}
seen := map[T]struct{}{}
var capLen int

for _, list := range lists {
capLen += len(list)
}

result := make([]T, 0, capLen)
seen := make(map[T]struct{}, capLen)

for _, list := range lists {
for _, e := range list {
Expand Down