What's the deal with Lazy Statics?

55 points Cosiamo

I'm building a csv parser for the company I work for and I'm using Regex to find dates and times. I'm optimizing it because the performance wasn't great, so I was going through forms and docs when I stumbled upon OnceCell which has the 'Lazy' struct. I followed the example and before it would take 76 secs to parse a 1.2 mil row csv file and now it only takes 10 sec.

I've been looking as to why there's such a dramatic improvement but I can't find anything that explains it well. Does anyone know why?

Example code:

Before

pub fn is_date(&self) -> bool {  
    let date_regex = Regex::new(r"^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$").unwrap();
    match date_regex.captures(&self.b) {
        Some(_) => true, 
        None => false,  
    }  
}

After

static DATE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$").unwrap()
});

pub fn is_date(&self) -> bool {  
    match DATE.captures(&self.b) {
        Some(_) => true, 
        None => false,  
    }  
}