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

后端 未结 21 2031
别那么骄傲
别那么骄傲 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 05:06

    I'd extrapolate tster's reply to "switch over a custom hash function", assuming that the code generator creates a lookup table, or - failing that - building the lookup table myself.

    The custom hash function should be simple, e.g.:

    (int)ActivCode[0]*2 + ActivCode.Length-1
    

    This would require a table of 51 elements, easily kept in L1 cache, under the following assumptions:

    • Input data must already be validated
    • empty string must be handled sepsarately
    • no two-character-codes start with the same character
    • adding new cases is hard

    the empty string case could be incorporated if you could use an unsafe access to ActivCode[0] yielding the '\0' terminator.

    0 讨论(0)
  • 2021-01-30 05:09

    I'd use a dictionary for the key value pairs and take advantage of the O(1) lookup time.

    0 讨论(0)
  • 2021-01-30 05:11

    +1 for using a dictionary. Not necessarily for optimization, but it'd be cleaner.

    I would probably use constants for the strings as well, though i doubt that'd buy you anything performance wise.

    0 讨论(0)
提交回复
热议问题