Repeated Work In Loop (ARCH5072)
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
Key go.performance.repeated-work-in-loop · Severity info · Category performance
A computation whose inputs do not depend on the loop variable re-runs on every iteration. Hoist loop-invariant expressions out of the loop.
Incorrect
Section titled “Incorrect”func match(items []string, prefix string) []string { var out []string for _, item := range items { if strings.HasPrefix(item, strings.ToLower(prefix)) { out = append(out, item) } } return out}Correct
Section titled “Correct”func match(items []string, prefix string) []string { lower := strings.ToLower(prefix) var out []string for _, item := range items { if strings.HasPrefix(item, lower) { out = append(out, item) } } return out}Move computations whose inputs don’t depend on the loop variable before the loop.