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

前端 未结 6 1097
星月不相逢
星月不相逢 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:18

    Like yossi1981 said, a switch could be optimized of beeing a fast lookup-table but there is not guarantee, every compiler has other algorithms to determine whether to implement the switch as consecutive if's or as fast lookup table, or maybe a combination of both.

    To gain a fast switch your values should meet the following rule: they should be consecutive, that is e.g. 0,1,2,3,4. You can leave some values out but things like 0,1,2,34,43 are extremely unlikely to be optimized.

    The question really is: is the performance of such significance in your application? And wouldn't a map which loads its values dynamically from a file be more readable and maintainable instead of a huge statement which spans multiple pages of code?

提交回复
热议问题