Most efficeint way to see if variable is equal to any of these strings
I have a list of five strings. I want to see if the variable passed in is equal to any of these five strings. Is there a better way than doing an if/else or case sta开发者_如何学编程tement?
Assuming I understand what you mean, here's an ugly, but simple to understand method, and we put the strings in to a list:
var data = new List<string>();
// add some:
data.Add("Stack");
data.Add("Overflow");
data.Add("Is");
data.Add("Awesome");
string test = "Stack";
// does our list contain our test?
bool found = data.Contains(test);
I believe using a HashSet is much more efficient!
Using the test program shown below, I get the following results:
list time: 558 hash time: 150
list time: 150 hash time: 7
list time: 138 hash time: 7
list time: 138 hash time: 7
list time: 142 hash time: 3
list time: 138 hash time: 3
list time: 142 hash time: 3
list time: 142 hash time: 3
list time: 138 hash time: 7
list time: 223 hash time: 7
Yes, it probably is the worst-case scenario for the list, as my test is looking for the last entry in the sequence, but it makes the point. Contains() has to search linearly the entire linked list (that's what List is) which is O(n), where as the HashSet is using a hash function to find the key, which is a constant time operation O(1)
Here is my test program:
static void Main(string[] args)
{
var list = new List<string>();
var hash = new HashSet<string>();
for (int i = 0; i < 1000; i++)
{
list.Add(i.ToString());
hash.Add(i.ToString());
}
Stopwatch sw = new Stopwatch();
for (int j = 0; j < 10; j++)
{
sw.Start();
bool isFound1 = list.Contains("999");
sw.Stop();
var time1 = sw.Elapsed;
sw.Reset();
sw.Start();
bool isFound2 = hash.Contains("999");
sw.Stop();
var time2 = sw.Elapsed;
sw.Reset();
Console.WriteLine("list time: " + time1.Ticks);
Console.WriteLine("hash time: " + time2.Ticks);
Console.WriteLine();
}
}
Assuming the passed variable is also a string, you might want to look into this question. Just put your five strings in a string[]
(or List
, or anything that implements IEnumerable
for that matter) and call IEnumerable<string>.Contains
to see if it is equal to any of the strings. (note that this will not tell you which string it is equal to, but since you haven't actually asked for that...)
Did you see this:
To check if a string contains an element from a list (of strings) - Is there a better way to write this code?
And this article compares performance of 4 different methods of doing the same: http://www.tkachenko.com/blog/archives/000682.html
精彩评论