Fastest way to find a string in C #?

What is the fastest way to implement something like this in C #:

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

Notice this is just an example. I just need to do low-level filtering for some values ​​that start as strings. I could intern them, but you still need to maintain a comparison of one or more lines. Value: either a string for comparing strings (1 filter), or a string exists in the list of strings (several filters).

+6
performance string c #
source share
3 answers

You can do this faster using a HashSet<T> , especially if you are going to add a lot more elements:

 private HashSet<string> _myMatches = new HashSet<string>() { "one", "two", "three" }; private bool Exists(string foo) { return _myMatches.Contains(foo); } 

This will print a List<T> , since HashSet<T>.Contains is an O (1) operation.

List<T> Contains the method, on the other hand, O (N). It will search the entire list (until a match is found) for each call. This will slow down as more items are added.

+17
source share

Hash tables are your friends for quick row searches.

Check out a good tutorial on Working with HashTable in C # 2.0

0
source share

You will need a profile. And you mean a quick search (i.e., counting initialization time)?

@Elf King already mentioned Hash Tables, which I was going to point out to you (specifically HashSet<T> )

0
source share

All Articles