switch case VS map

xiaolomg 2013-01-16 09:15:25
今天想到这个问题,在网上搜了,真是出乎意料:
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进行如此优化,各位大神来讨论下啊。
...全文
324 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
swordtan 2013-01-17
  • 打赏
  • 举报
回复
这个还真不知道,估计switch优化的时候,采用类似hash的方式达到0(1)的速度,现在的编译器越做越好了
jackzhhuang 2013-01-17
  • 打赏
  • 举报
回复
switch是比较快的,但文章也说了,map是动态的。
帅得不敢出门 2013-01-17
  • 打赏
  • 举报
回复
在各case值相近的情况下,switch可能会比if else 快。
赵4老师 2013-01-17
  • 打赏
  • 举报
回复
不要低估编译器release版输出时对switch语句优化的能力。 VS IDE中想看release版输出时switch语句对应的汇编指令,可以在switch前临时加一句__asm int 3,然后先重建所有、再按F5、再按Alt+8
  • 打赏
  • 举报
回复
switch在特定的情况下优化的很厉害。
taodm 2013-01-16
  • 打赏
  • 举报
回复
鬼扯的英文。 你在1~100000的值域内随机取10个值switch自己试,看哪个编译器可以给你O(1)

64,648

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧