Reputation: 611
Is there anyway of improving the speed / efficiency of this method? It is called tens of thousands of time in my code, and is slowing down the system I am developing.
Basically, 'Field' has a 'Name' and a 'Value' and I need to check if it matches the name/value of the corresponding property in my class. Field.Value may also be a regular expression. I imagine the regex is slowing things down a bit.
private bool FieldMatch(Field field)
{
var propValue = GetPropertyValue(field.Name);
var regEx = new Regex(field.Value, RegexOptions.IgnoreCase);
var stringMatch = string.Compare(propValue, field.Value, StringComparison.InvariantCultureIgnoreCase )
return (stringMatch == 0) || regEx.IsMatch(propValue);
}
Upvotes: 0
Views: 55
Reputation: 611
I have two solutions to this issue.
One is to add a pre-compiled Regex to the Field class like so:
public class Field
{
public string Name { get; set; } // Should ultimately be an enum.
public string Value { get; set; }
public Regex RegexValue
{
get {
return _regexValue ?? (_regexValue =
new Regex(Value, RegexOptions.Compiled | RegexOptions.IgnoreCase));
}
}
private Regex _regexValue;
}
private bool FieldMatch(Field field)
{
var propValue = GetPropertyValue(field.Name);
var stringMatch = string.Compare(propValue, field.Value, StringComparison.InvariantCultureIgnoreCase);
return (stringMatch == 0) || field.RegexValue.IsMatch(propValue);
}
The other is to use the static Regex like so:
private bool FieldMatch(Field field)
{
var propValue = GetPropertyValue(field.Name);
var stringMatch = string.Compare(propValue, field.Value, StringComparison.InvariantCultureIgnoreCase);
return (stringMatch == 0) || Regex.IsMatch(propValue, field.Value);
}
Which one is quickest depends on the scale of the system, but both are a very good improvement over the previous solution
Upvotes: 1