我有大约 10 万封 Outlook 邮件项目,每个正文大约有 500-600 个字符。我有一个包含 580 个关键字的列表,必须搜索每个正文,然后将这些词附加在底部。
我相信我已经提高了大部分功能的效率,但仍然需要很多时间。即使是 100 封电子邮件,也需要大约 4 秒。
我为每个关键字列表运行两个函数(每个列表 290 个关键字)。
public List<string> Keyword_Search(HtmlNode nSearch)
{
var wordFound = new List<string>();
foreach (string currWord in _keywordList)
{
bool isMatch = Regex.IsMatch(nSearch.InnerHtml, "\\b" + @currWord + "\\b",
RegexOptions.IgnoreCase);
if (isMatch)
{
wordFound.Add(currWord);
}
}
return wordFound;
}
有什么方法可以提高这个函数的效率吗?
另一件可能会减慢速度的事情是我使用 HTML Agility Pack 在一些节点中导航并拉出正文 (nSearch.InnerHtml)。 _keywordList 是列表项,而不是数组。
最佳答案
我假设 COM 调用 nSearch.InnerHtml
非常慢,并且您对要检查的每个单词都重复调用。您可以简单地缓存调用的结果:
public List<string> Keyword_Search(HtmlNode nSearch)
{
var wordFound = new List<string>();
// cache inner HTML
string innerHtml = nSearch.InnerHtml;
foreach (string currWord in _keywordList)
{
bool isMatch = Regex.IsMatch(innerHtml, "\\b" + @currWord + "\\b",
RegexOptions.IgnoreCase);
if (isMatch)
{
wordFound.Add(currWord);
}
}
return wordFound;
}
Jeff Yates 建议的另一种优化。例如。通过使用单一模式:
string pattern = @"(\b(?:" + string.Join("|", _keywordList) + @")\b)";
关于c# - 提高正则表达式效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2545482/