.NET C# Regular expression optimization - can I solve this performance issue?
I have a performance issue with some Regular expression code I've written.
There are two regular expressions involved:
The first is just a straight text search, passed to the following C# code so I can count the instances within the text:
textMatchRegExp1: string that im searching for
The second开发者_开发技巧 matches text that exists within html comments, allowing for white space.
textMatchRegExp2: <!--.*(-->){0}.*(string that im searching for)+.*(<!--){0}.*-->
The purpose of these expressions is so that I can find if text appears in the html source for a page, but is not within comments. If the total count found by textMatchRegExp1 is greater than textMatchRegExp2, then there must be instances of the text not found in comments.
I'm aware this doesn't look the slickest of methods, I considered negative / positive look behind, but that didn't seem to fit my problem as far as I could work out (please correct me if I'm wrong).
I have settled on this method as shows this method works very reliably through unit testing, even where the text exists multiple times within the same comment.
My problem is that this is proving to be unacceptably slow for some web pages that I test, just freezing the application entirely is some cases.
Is there anyway I can optimize the reg ex searches? I've included the full C# code for context.
public static bool StringExistsInSource(string text, string html)
{
text = text.ToLower();
text = text.Replace(" ", @"\s+"); // Add in white space to match
html = html.ToLower();
// Matches up all instances of text, including those in comments
string textMatchRegExp = text;
// Matches up comments containing text
string textWithinCommentRegExp = "<!--.*(-->){0}.*(" + text + ")+.*(<!--){0}.*-->";
// Read total count of ALL matches
int textMatchCount = Regex.Matches(html, textMatchRegExp).Count;
int textWithinCommentCount = 0;
// Iterate through comments containing given text
foreach (Match m in Regex.Matches(html, textWithinCommentRegExp))
{
textWithinCommentCount += Regex.Matches(m.ToString(), textMatchRegExp).Count;
}
// If text exists outside of comments,
// the total match count will be higher than the
// text within comments count
return textMatchCount > textWithinCommentCount;
}
If you are in the case where you're searching for the same text across different html pages (as opposed to searching for different values of "text" within the same html page) you could try compiling your regex with RegexOptions.Compiled
If you're not reusing your regex, however, compilation would not give you any performancce benefit (since the first time you use your regex is slow anyway) and may also bloat your application's memory footprint (since, if I remember correctly, the generated code that comes from the compilation of your regex can't be garbage collected)
精彩评论