Skip to content

Commit 1d4a72f

Browse files
authored
perf(coderd/util/slice): refactor unique method for large lists (#8925)
1 parent 05054c6 commit 1d4a72f

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

coderd/util/slice/slice.go

+8-6
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,19 @@ func Overlap[T comparable](a []T, b []T) bool {
3838
}
3939

4040
// Unique returns a new slice with all duplicate elements removed.
41-
// This is a slow function on large lists.
42-
// TODO: Sort elements and implement a faster search algorithm if we
43-
// really start to use this.
4441
func Unique[T comparable](a []T) []T {
4542
cpy := make([]T, 0, len(a))
43+
seen := make(map[T]struct{}, len(a))
44+
4645
for _, v := range a {
47-
v := v
48-
if !Contains(cpy, v) {
49-
cpy = append(cpy, v)
46+
if _, ok := seen[v]; ok {
47+
continue
5048
}
49+
50+
seen[v] = struct{}{}
51+
cpy = append(cpy, v)
5152
}
53+
5254
return cpy
5355
}
5456

0 commit comments

Comments
 (0)