FxC1802 : ConsiderMakingRegexReadOnlyAndCompiled

TypeName ConsiderMakingRegexReadOnlyAndCompiled
CheckId FxC1802
Category FxCopContrib.Performance
Breaking Change Non-breaking

Cause

A Regex instance or method is being called with a constant value for the expression, but RegexOptions.Compiled is not used and the Regex instance is not saved for future re-use.

Rule Description

When you pass a string to the constructor or one of the static methods of Regex, the expression will be parsed and if requested compiled. Compilation takes additional time, but will make future use of the same expression faster. If the RegexOptions.Compiled flag is not passed to the constructor or when you're using the static methods the expression will be converted to a state machine. By default only 17 of these state machines are cached.

How to fix violations

Store your regular expressions in a static readonly field for future re-use, apply the RegexOptions.Compiled flag.

When to suppress warnings

The documentation clearly states when to use the RegexOptions.Compiled flag. You can suppress the warning if:
  • You're not able to re-use the regular expression
  • You don't want the first call to the regular expression to take the one-time performance hit required for compilation

Example

You use a Regular Expression to validate the contents of a string variable:

Bad Example
public bool IsValidProductCode(string value)
{
     return Regex.IsMatch(value, "[a-z]{3}:\\d+");
}

Good Example
private static readonly Regex ValidProductCodeRegex = new Regex("[a-z]{3}:\\d+", RegexOptions.Compiled);

public bool IsValidProductCode(string value)
{
     return ValidProductCodeRegex.IsMatch(value);
}

Last edited Feb 14, 2012 at 8:42 PM by jessehouwing, version 4

Comments

No comments yet.