Tip: No fancy collections like a Dictionary or complex if-else chains are required here.
And: The C# compiler (our friend) will try to improve the switch's performance based on its internal heuristic.
IsMoth: Contains a switch case with 7 moth names in it. If any of those strings equal the parameter, it returns true. We have a moth name.
Then: All the cases are lowercase. This results in a case-insensitive string switch.
Tip: The uppercase string "WHIPPET" was found to be a dog type. The value.ToLower() expression will match "whippet" in lowercase.ToLower
Note: In .NET Framework internals, null is like a 0 value, so it too is a constant—we call it the null literal constant.
So: We can use switches to tell the computer that "Height" is an abbreviation for "Ht."
Trim: We can use the Trim, TrimEnd, and TrimStart methods to try to normalize the input further.TrimTrimEnd, TrimStart
Here: We handle abbreviations in a string switch, and also remove ending spaces. Further string logic could be added.
Version 1: We use the string switch to test the tree name strings. The switch is run in a tight loop.
Version 2: We use an expression, which is compiled into something like a series of if-else statements.If
Result: The string switch statement is faster. If we cannot test for the most common string first, a string switch can improve performance.
So: It may be useful to test the code on a system before you deploy it. Things might be wrong on the Internet.
Note: To achieve even better performance, you can try reordering the strings in an optimal way.
Tree: For complex situations where we have many strings and want to test them in a loop, consider a directed acyclic graph.Tree