C# performance of static string[] contains() (slooooow) vs. == operator
- by Andrew White
Hiya,
Just a quick query:
I had a piece of code which compared a string against a long list of values, e.g.
if(str == "string1" || str = "string2" || str == "string3" || str = "string4".
DoSomething();
And the interest of code clarity and maintainability I changed it to
public static string[] strValues = { "String1", "String2", "String3", "String4"};
...
if(strValues.Contains(str)
DoSomething();
Only to find the code execution time went from 2.5secs to 6.8secs (executed ca. 200,000 times).
I certainly understand a slight performance trade off, but 300%?
Anyway I could define the static strings differently to enhance performance?
Cheers.