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.
Fyi..
Using:
Checking for the first and last strings in the list then checking for a string not in the list: “xstring”
Executing 500,000 iterations, all times in milliseconds.
Interesting (if not unexpected) results when we change the strings in the list:
With “string99” as the none check.
For cases A and B looks like tests 2 and 3 have the advantage.
However, HashSet.Contains(string) is very efficient, not effected by list contents and has a clear syntax…might be the best choice.
Yes, it is true, I have no life.