I'm looking through a friend of mine's library because he asked about optimization and I came across a section of code like this:
long digit = 0;
switch (word) {
case "zero":
digit = 0;
break;
case "a":
case "one":
digit = 1;
break;
case "two":
digit = 2;
break;
case "three":
digit = 3;
break;
case "four":
digit = 4;
break;
case "five":
digit = 5;
break;
case "six":
digit = 6;
break;
case "seven":
digit = 7;
break;
case "eight":
digit = 8;
break;
case "nine":
digit = 9;
break;
case "ten":
digit = 10;
break;
case "eleven":
digit = 11;
break;
case "twelve":
digit = 12;
break;
case "thirteen":
digit = 13;
break;
case "fourteen":
digit = 14;
break;
case "fifteen":
digit = 15;
break;
case "sixteen":
digit = 16;
break;
case "seventeen":
digit = 17;
break;
case "eighteen":
digit = 18;
break;
case "nineteen":
digit = 19;
break;
case "twenty":
digit = 20;
break;
case "thirty":
digit = 30;
break;
case "fourty":
digit = 40;
break;
case "fifty":
digit = 50;
break;
case "sixty":
digit = 60;
break;
case "seventy":
digit = 70;
break;
case "eighty":
digit = 80;
break;
case "ninety":
digit = 90;
break;
}
return digit;
I've seen a few questions on here about exactly how a switch might work, but they conveniently don't mention cases with strings. Can a switch statement like the one above be optimized in any way?
You can put these in a Dictionary<string,int>
and return the int
for the string key.
var wordsToNumbers = new Dictionary<string,int>();
wordsToNumbers.Add("one", 1);
...
wordsToNumbers.Add("ninety", 90);
// elsewhere
return wordsToNumbers[word];
Note:
As others have noted in the comments - the idea is to build the dictionary once and reuse it. One way would be to use a field and populate it in a constructor, then use it in other methods.
As Oded said, you can put them in a Dictionary
. But in fact, the .NET compiler already does this for you: it builds a jump table (via a Dictionary<string, SomeDelegate>
) that allows to switch on the value in O(1).
That said, I actually find using a Dictionary<string, int>
more readable than a switch
here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With