From 8aef2201d817203a3ebd666457912efe3c5e68e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=80=8D=E9=81=A5?= Date: Tue, 21 Nov 2023 18:45:37 +0800 Subject: [PATCH] perf: Optimize the performance of union method, avoid repeated expansion --- intersect.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/intersect.go b/intersect.go index cf6cab3d..90312b88 100644 --- a/intersect.go +++ b/intersect.go @@ -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 {