What is more efficient a switch case or an std::map

前端 未结 6 1083
星月不相逢
星月不相逢 2020-12-28 13:57

I\'m thinking about the tokenizer here.
Each token calls a different function inside the parser.
What is more efficient:

  • A map of std::functions/boos
6条回答
  •  不思量自难忘°
    2020-12-28 14:30

    STL Map that comes with visual studio 2008 will give you O(log(n)) for each function call since it hides a tree structure beneath. With modern compiler (depending on implementation) , A switch statement will give you O(1) , the compiler translates it to some kind of lookup table. So in general , switch is faster.

    However , consider the following facts:

    The difference between map and switch is that : Map can be built dynamically while switch can't. Map can contain any arbitrary type as a key while switch is very limited to c++ Primitive types (char , int , enum , etc...).

    By the way , you can use a hash map to achieve nearly O(1) dispatching (though , depending on the hash table implementation , it can sometimes be O(n) at worst case). Even though , switch will still be faster.

    Edit

    I am writing the following only for fun and for the matter of the discussion

    I can suggest an nice optimization for you but it depends on the nature of your language and whether you can expect how your language will be used.

    When you write the code: You divide your tokens into two groups , one group will be of very High frequently used and the other of low frequently used. You also sort the high frequently used tokens. For the high frequently tokens you write an if-else series with the highest frequently used coming first. for the low frequently used , you write a switch statement.

    The idea is to use the CPU branch prediction in order to even avoid another level of indirection (assuming the condition checking in the if statement is nearly costless). in most cases the CPU will pick the correct branch without any level of indirection . They will be few cases however that the branch will go to the wrong place. Depending on the nature of your languege , Statisticly it may give a better performance.

    Edit : Due to some comments below , Changed The sentence telling that compilers will allways translate a switch to LUT.

提交回复
热议问题