Skip to content

rust.regex_compile

Performance High

Detects regex compilation inside loops or hot paths, causing repeated parsing overhead.

Regex in loops:

  • Parses repeatedly — Same pattern compiled per iteration
  • Wastes CPU — 10-100x slower than cached
  • Hurts latency — Measurable request delays
// ❌ Before (compiling in loop)
for line in lines {
let re = Regex::new(r"\d+")?; // Compiles every iteration!
if re.is_match(line) {
count += 1;
}
}
// ✅ After (compile once with lazy_static)
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
static ref NUMBER_RE: Regex = Regex::new(r"\d+").unwrap();
}
for line in lines {
if NUMBER_RE.is_match(line) {
count += 1;
}
}
  • Regex::new inside loops
  • Regex compilation in request handlers
  • Missing static regex patterns

Unfault can hoist regex to lazy_static or once_cell.