Compile once
If we have a function that has a regex in it, then every time we call that function the regex engine has to "compile" the regex to its internal format. This takes time and it is rather unnecessary waste of time. After all the same regex will compile the same way no matter how many times the function is called.
The multiple compilation can be avoided by using the once_cell crate.
Cargo.toml
[package]
name = "regex-compile-once"
version = "0.1.0"
edition = "2024"
[dependencies]
once_cell = "1.21.3"
regex = "1.11.1"
Code
use once_cell::sync::Lazy; use regex::Regex; fn main() { let rows = vec![ String::from("Hello, world!"), String::from("This is some text"), ]; for row in rows { check_something(&row); } } fn check_something(text: &str) { static RE: Lazy<Regex> = Lazy::new(|| { println!("Compiling regex"); Regex::new(r"Hello").unwrap() }); let is = RE.is_match(text); println!("Is match: {}", is); }
In the output we can see that it was compiled only once.
Compiling regex
Is match: true
Is match: false