Skip to content

Commit

Permalink
perf: Optimize the performance of union method, avoid repeated expans…
Browse files Browse the repository at this point in the history
…ion (#397)

Co-authored-by: 逍遥 <[email protected]>
  • Loading branch information
cwb2819259 and 逍遥 authored Jun 28, 2024
1 parent 07e3675 commit 7cce15b
Showing 1 changed file with 8 additions and 2 deletions.
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 i := range lists {
for j := range lists[i] {
Expand Down

0 comments on commit 7cce15b

Please sign in to comment.