perf(coderd/util/slice): refactor unique method for large lists (#8925)

This commit is contained in:
Cem 2023-08-08 18:02:52 +03:00 committed by GitHub
parent 05054c6a0a
commit 1d4a72f43f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 6 deletions

View File

@ -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
}