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

Regex Recompiled In Loop (ARCH5073)

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

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.

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
}
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.