How to make regex replace faster

It takes about 0.5ms on my computer, but I wonder is there any way to improve the speed? Thanks.

use std::time::Instant;
use regex::Regex;

fn main() {
    let str = "Coast Base 我 们 one more 到 付 time.";
    let start = Instant::now();
    let re = Regex::new(r"([^\x00-\x7F]) ([^\x00-\x7F])").unwrap();
    let mut str_cow = re.replace_all(str, "$1$2");
    println!("time: {:?}", Instant::now().duration_since(start).as_secs_f64()*1000.0 );
    println!("{:?}", str_cow);

Did you compile with --release?

Honestly, you're probably seeing timing jitter. I would recommend using a real benchmark library to measure things like this, such as bencher or (disclosure: I maintain

Additionally, you're timing the compilation of the regex as well as the replacement. Maybe that's what you want, but for most uses of regexes you'd compile the regex once and match it many times, so your test may not be representative of your actual usage.


Yes, I need to compile the regex once and match many times. So after using lazy_static for all "compilation of the regex", the problem got solved.
Thank you for your quick and amazing response.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.