From 1d4a72f43f805b1903b99c9cfaed8534531b8b91 Mon Sep 17 00:00:00 2001 From: Cem Date: Tue, 8 Aug 2023 18:02:52 +0300 Subject: [PATCH] perf(coderd/util/slice): refactor unique method for large lists (#8925) --- coderd/util/slice/slice.go | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/coderd/util/slice/slice.go b/coderd/util/slice/slice.go index 9909fe2b72..0bc5920ce3 100644 --- a/coderd/util/slice/slice.go +++ b/coderd/util/slice/slice.go @@ -38,17 +38,19 @@ func Overlap[T comparable](a []T, b []T) bool { } // Unique returns a new slice with all duplicate elements removed. -// This is a slow function on large lists. -// TODO: Sort elements and implement a faster search algorithm if we -// really start to use this. func Unique[T comparable](a []T) []T { cpy := make([]T, 0, len(a)) + seen := make(map[T]struct{}, len(a)) + for _, v := range a { - v := v - if !Contains(cpy, v) { - cpy = append(cpy, v) + if _, ok := seen[v]; ok { + continue } + + seen[v] = struct{}{} + cpy = append(cpy, v) } + return cpy }