Your first code sample will be slower and allocate more memory since:
new String[] { "test1", "test2", "test3", "test4"}
will create a new array on every invocation, and there is a (small) perf cost associated with iterating over an array.
You could offset the creation cost, by storing this array in a static field
(i.e. just create it once):
private static string[] ValidValues = {"test1", "test2", "test3", "test4"};
Your second code sample will be faster, but also is more verbose (since MySelecredFooValue
is repeated). Consider changing it to:
switch (MySelecredFooValue)
{
case "test1":
case "test2":
case "test3":
case "test4":
//Your logic here
break;
}
If you really like the array approach, and want better performance, try:
// declare this outside of your function
private static HashSet<string> ValidValues = new HashSet<string>() {"test1", "test2", "test3", "test4"};
// code for inside the function
if (ValidValues.Contains(MySelecredFooValue))
{
//Your logic here
}
For small numbers of entries (like 3 or 4), performance of a HashSet
often isn't better than an array - but if there are many more entries (e.g. 20) then usually a HashSet
will substantially outperform an array for Contains
calls.