تخطَّ إلى المحتوى

Inefficient Membership Test (ARCH5075)

هذا المحتوى غير متوفر بلغتك بعد.

Key go.performance.inefficient-membership-test · Severity warning · Category performance

Repeatedly checking membership against a slice scans O(n) each time. Especially inside a loop, use a map[T]struct{} for O(1) lookups.

func selectAllowed(items, allowed []string) []string {
var out []string
for _, item := range items {
for _, a := range allowed {
if item == a {
out = append(out, item)
}
}
}
return out
}
func selectAllowed(items, allowed []string) []string {
set := make(map[string]struct{}, len(allowed))
for _, a := range allowed {
set[a] = struct{}{}
}
var out []string
for _, item := range items {
if _, ok := set[item]; ok {
out = append(out, item)
}
}
return out
}

Use a map for repeated membership checks instead of scanning a slice.