我并不完全清楚您的搜索条件是什么。您暗示匹配字符串始终位于末尾。所以这里有一些简单的时间测试来给出一个大致的想法。测试搜索两个字符串,其中第一个不存在于目标中,第二个存在。
string.IndexOf 240 nanoseconds (to find string anywere in string, not just at end)
string.EndsWith 210 nanoseconds
Regex.Match 1,285 nanoseconds
precompiled Regex 648 nanoseconds
测试代码如下。它使用了我编写的一个小基准测试实用程序,可以从结果中消除时序测试开销(括号循环等)。我不是正则表达式专家,所以希望我的搜索模式可以与字符串测试相媲美。
string s = "zzzzzzzzzzzzzzzzzzzzzzzsomething";
string search1 = "thinker";
string search2 = "something";
int pos = 0;
new Bench().Time("string.IndexOf", (c) => {
for (int i = 0; i < c; i++) {
if ((pos = s.IndexOf(search1)) < 0) {
pos = s.IndexOf(search2);
}
}
});
bool found = false;
new Bench().Time("string.EndsWith", (c) => {
for (int i = 0; i < c; i++) {
if (!(found = s.EndsWith(search1))) {
found = s.EndsWith(search2);
}
}
});
string pattern = "(" + search1 + "|" + search2 + ")$";
Match match = null;
new Bench().Time("Regex.Match", (c) => { for (int i = 0; i < c; i++) match = Regex.Match(s, pattern); });
Regex regex = new Regex(pattern, RegexOptions.Compiled);
new Bench().Time("precompiled", (c) => { for (int i = 0; i < c; i++) match = regex.Match(s); });