1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

refactoring: memory optimization for unique slice

This commit is contained in:
dudaodong
2024-08-08 10:51:33 +08:00
parent 3e7f94b03e
commit 286e10d189

View File

@@ -771,15 +771,19 @@ func UpdateAt[T any](slice []T, index int, value T) []T {
// Unique remove duplicate elements in slice. // Unique remove duplicate elements in slice.
// Play: https://go.dev/play/p/AXw0R3ZTE6a // Play: https://go.dev/play/p/AXw0R3ZTE6a
func Unique[T comparable](slice []T) []T { func Unique[T comparable](slice []T) []T {
result := []T{} result := make([]T, 0, len(slice))
exists := map[T]bool{} seen := make(map[T]struct{}, len(slice))
for _, t := range slice {
if exists[t] { for i := range slice {
if _, ok := seen[slice[i]]; ok {
continue continue
} }
exists[t] = true
result = append(result, t) seen[slice[i]] = struct{}{}
result = append(result, slice[i])
} }
return result return result
} }