Skip to content

go.regex_compile

Performance Medium

Detects regex patterns compiled repeatedly inside loops or frequently-called functions.

Compiling regex in hot paths:

  • Wastes CPU — Regex compilation is expensive
  • Increases latency — Each request pays compilation cost
  • Scales poorly — Impact grows with traffic
  • Triggers GC pressure — Allocates memory repeatedly
// ❌ Before (compiled every call)
func validateEmail(email string) bool {
pattern := regexp.MustCompile(`^[\w.-]+@[\w.-]+\.\w+$`)
return pattern.MatchString(email)
}
// ✅ After (compiled once)
var emailPattern = regexp.MustCompile(`^[\w.-]+@[\w.-]+\.\w+$`)
func validateEmail(email string) bool {
return emailPattern.MatchString(email)
}
  • regexp.Compile() inside functions
  • regexp.MustCompile() inside loops
  • Repeated pattern compilation in handlers

Unfault moves regex compilation to package level:

// Moved to package level
var _pattern = regexp.MustCompile(`\d{4}-\d{2}-\d{2}`)