From 286e10d1895b8126d300d62a09ddb5ae15d0bd85 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Thu, 8 Aug 2024 10:51:33 +0800 Subject: [PATCH] refactoring: memory optimization for unique slice --- slice/slice.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/slice/slice.go b/slice/slice.go index 62cd83c..89a62c8 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -771,15 +771,19 @@ func UpdateAt[T any](slice []T, index int, value T) []T { // Unique remove duplicate elements in slice. // Play: https://go.dev/play/p/AXw0R3ZTE6a func Unique[T comparable](slice []T) []T { - result := []T{} - exists := map[T]bool{} - for _, t := range slice { - if exists[t] { + result := make([]T, 0, len(slice)) + seen := make(map[T]struct{}, len(slice)) + + for i := range slice { + if _, ok := seen[slice[i]]; ok { continue } - exists[t] = true - result = append(result, t) + + seen[slice[i]] = struct{}{} + + result = append(result, slice[i]) } + return result }