go.regex_compile
Performance
Medium
Detects regex patterns compiled repeatedly inside loops or frequently-called functions.
Why It Matters
Section titled “Why It Matters”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
Example
Section titled “Example”// ❌ 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)}What Unfault Detects
Section titled “What Unfault Detects”regexp.Compile()inside functionsregexp.MustCompile()inside loops- Repeated pattern compilation in handlers
Auto-Fix
Section titled “Auto-Fix”Unfault moves regex compilation to package level:
// Moved to package levelvar _pattern = regexp.MustCompile(`\d{4}-\d{2}-\d{2}`)