Skip to content

Regex performance: use static Regex.IsMatch #297

@akamud

Description

@akamud

We could diagnose code using Regex in a way that gives poor performances.

Creating a new Regex every time will give you a bad performance:

public static bool IsValidCurrency(string currencyValue)
{
  string pattern = @"\p{Sc}+\s*\d+";
  Regex currencyRegex = new Regex(pattern);
  return currencyRegex.IsMatch(currencyValue);
}

If this method is called multiple times, you should be using the static Regex.IsMatch method, as that can be cached and won't be interpreted every time you call the method, it will give you better performance.
This is quite common on email address validation during registration, or validating user input (like the currency example above or Zip codes).

Code fix:

public static bool IsValidCurrency(string currencyValue)
{
  string pattern = @"\p{Sc}+\s*\d+";
  return Regex.IsMatch(currencyValue, pattern); 
}

I created a project showing the difference in performance, testing this case with only 10 runs shows that instance method is almost 3 times slower.

Instance took 0.000639 seconds
Static took   0.000240 seconds

Running this 100,000 times gives these results:

Instance took 0.3786505 seconds
Static took   0.0717608 seconds

I'm sure there are more cases of improving Regex performance that we could diagnose, but this one is pretty straightforward. What do you think?

Diagnostic Id: CC0081
Severity: Info
Style: Performance

@akamud is working on it.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions