Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to optimize large switch on strings?

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?

like image 248
Corey Ogburn Avatar asked Nov 28 '22 18:11

Corey Ogburn


2 Answers

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.

like image 40
Oded Avatar answered Dec 01 '22 08:12

Oded


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.

like image 57
Konrad Rudolph Avatar answered Dec 01 '22 08:12

Konrad Rudolph