Reputation: 25
I have used this predicate builder to create filter expression to use with LINQ queries. So while building have included regular expression to match certain condition,but it takes too long to execute any idea why or how to improve ?
For example:
stringvalue.contains(word)
executes faster than:
Regex.IsMatch(stringvalue,@"\b"+word+@"\b",regexoptions.compiled)
Upvotes: -4
Views: 142
Reputation: 67477
Well of course it does, the regular expression call you wrote does a lot more than just checking if a substring is present or not:
It checks for whole words only. "arf".Contains("a") == true
, but Regex.IsMatch("arf", @"\ba\b") == false
.
It invokes the compiler to build an entire new chunk of code, creates a new app domain and loads it in there, then calls it (across app domains).
The latter is especially unwarranted, since your regex changes every search, there's no reuse to amortize the cost of compiling and loading the generated code. Absolutely remove the RegexOptions.Compiled
flag.
As to regular expressions in general, I recommend updating to .Net 5, there have been marked improvements of up to 95% for regex matching, especially simple ones like yours.
Upvotes: 1