Regex Recompiled In Loop (ARCH5073)
Esta página aún no está disponible en tu idioma.
Key go.performance.regex-recompiled-in-loop · Severity warning · Category performance
Calling regexp.MustCompile inside a loop recompiles the same pattern on every iteration, which is expensive. Compile the pattern once outside the loop.
Incorrect
Section titled “Incorrect”func filter(lines []string) []string { var out []string for _, line := range lines { re := regexp.MustCompile(`^\d+`) if re.MatchString(line) { out = append(out, line) } } return out}Correct
Section titled “Correct”var numRe = regexp.MustCompile(`^\d+`)
func filter(lines []string) []string { var out []string for _, line := range lines { if numRe.MatchString(line) { out = append(out, line) } } return out}Compile the regex once outside the loop, ideally as a package-level var.