How would you make this switch statement as fast as possible?

后端 未结 21 2073
别那么骄傲
别那么骄傲 2021-01-30 04:17

2009-12-04 UPDATE: For profiling results on a number of the suggestions posted here, see below!


The Question

Consider the following very

21条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-30 04:53

    If you know how often the various codes show up, the more common ones should go at the top of the list, so fewer comparisons are done. But let's assume you don't have that.

    Assuming the ActivCode is always valid will of course speed things up. You don't need to test for null or the empty string, and you can leave off one test from the end of the switch. That is, test for everything except Y, and then return DIRECTEDGE if no match is found.

    Instead of switching on the whole string, switch on its first letter. For the codes that have more letters, put a second test inside the switch case. Something like this:

    switch(ActivCode[0])
    {
       //etc.
       case 'B':
          if ( ActivCode.Length == 1 ) return MarketDataExchange.BSE; 
          else return MarketDataExchange.BATS;
          // etc.
    }
    

    It would be better if you could go back and change the codes so they are all single characters, because you would then never need more than one test. Better yet would be using the numerical value of the enum, so you can simply cast instead of having to switch/translate in the first place.

提交回复
热议问题