读书人

switch case VS 地图

发布时间: 2013-02-19 11:11:40 作者: rapoo

switch case VS map
今天想到这个问题,在网上搜了,真是出乎意料:
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.

顿时打破我之前的观点,不知道Vs2008是否对switch进行如此优化,各位大神来讨论下啊。
[解决办法]
鬼扯的英文。
你在1~100000的值域内随机取10个值switch自己试,看哪个编译器可以给你O(1)
[解决办法]
switch在特定的情况下优化的很厉害。
[解决办法]
在各case值相近的情况下,switch可能会比if else 快。

[解决办法]
switch是比较快的,但文章也说了,map是动态的。
[解决办法]
这个还真不知道,估计switch优化的时候,采用类似hash的方式达到0(1)的速度,现在的编译器越做越好了
[解决办法]
不要低估编译器release版输出时对switch语句优化的能力。
VS IDE中想看release版输出时switch语句对应的汇编指令,可以在switch前临时加一句__asm int 3,然后先重建所有、再按F5、再按Alt+8

读书人网 >C++

热点推荐