mirror of
https://github.com/coder/coder.git
synced 2025-07-09 11:45:56 +00:00
perf(coderd/util/slice): refactor unique method for large lists (#8925)
This commit is contained in:
@ -38,17 +38,19 @@ func Overlap[T comparable](a []T, b []T) bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Unique returns a new slice with all duplicate elements removed.
|
// 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 {
|
func Unique[T comparable](a []T) []T {
|
||||||
cpy := make([]T, 0, len(a))
|
cpy := make([]T, 0, len(a))
|
||||||
|
seen := make(map[T]struct{}, len(a))
|
||||||
|
|
||||||
for _, v := range a {
|
for _, v := range a {
|
||||||
v := v
|
if _, ok := seen[v]; ok {
|
||||||
if !Contains(cpy, v) {
|
continue
|
||||||
cpy = append(cpy, v)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
seen[v] = struct{}{}
|
||||||
|
cpy = append(cpy, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
return cpy
|
return cpy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user