在C#中找到字符串的最快方法?

Son*_*oul 6 c# string performance

在C#中实现类似内容的最快方法是什么:

  private List<string> _myMatches = new List<string>(){"one","two","three"};
  private bool Exists(string foo) {
      return _myMatches.Contains(foo);
  }
Run Code Online (Sandbox Code Playgroud)

请注意,这只是一个例子.我只需要对源自字符串的某些值执行低级别过滤.我可以实习他们,但仍然需要支持一个或多个字符串的比较.含义,字符串到字符串比较(1个过滤器),或者字符串是否存在于字符串列表中(多个过滤器).

Ree*_*sey 18

你可以通过使用a来加快速度HashSet<T>,特别是如果你要添加更多的元素:

private HashSet<string> _myMatches = new HashSet<string>() { "one", "two", "three" };

private bool Exists(string foo)
{
    return _myMatches.Contains(foo);
}
Run Code Online (Sandbox Code Playgroud)

这将击败一个List<T>因为HashSet<T>.Contains是O(1)操作.

List<T>另一方面,包含方法是O(N).它将在每次通话时搜索整个列表(直到找到匹配项).随着更多元素的添加,这将变得更慢.