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

后端 未结 21 1999
别那么骄傲
别那么骄傲 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:46

    I'd roll my own fast hash function and use an integer switch statement to avoid string comparisons:

    int  h = 0;  
    
    // Compute fast hash: A[0] + A[1]*0x100
    if (ActivCode.Length > 0)
        h += (int) ActivCode[0];
    if (ActivCode.Length > 1)
        h += (int) ActivCode[1] << 8;  
    
    // Find a match
    switch (h)
    {
        case 0x0000:  return MarketDataExchange.NBBO;        // ""
        case 0x0041:  return MarketDataExchange.AMEX;        // "A"
        case 0x0042:  return MarketDataExchange.BSE;         // "B"
        case 0x5442:  return MarketDataExchange.BATS;        // "BT"
        case 0x0043:  return MarketDataExchange.NSE;         // "C"
        case 0x574D:  return MarketDataExchange.CHX;         // "MW"
        case 0x004E:  return MarketDataExchange.NYSE;        // "N"
        case 0x4150:  return MarketDataExchange.ARCA;        // "PA"
        case 0x0051:  return MarketDataExchange.NASDAQ;      // "Q"
        case 0x4451:  return MarketDataExchange.NASDAQ_ADF;  // "QD"
        case 0x0057:  return MarketDataExchange.CBOE;        // "W"
        case 0x0058:  return MarketDataExchange.PHLX;        // "X"
        case 0x0059:  return MarketDataExchange.DIRECTEDGE;  // "Y"
        default:      return MarketDataExchange.NONE;
    }
    

    My tests show that this is about 4.5 times faster than the original code.

    If C# had a preprocessor, I'd use a macro to form the case constants.

    This technique is faster than using a hash table and certainly faster than using string comparisons. It works for up to four-character strings with 32-bit ints, and up to 8 characters using 64-bit longs.

提交回复
热议问题