How does switch compile in Visual C++ and how optimized and fast is it?(在 Visual C++ 中 switch 是如何编译的,它的优化和速度如何?)
问题描述
当我发现我只能在 C++ 的 switch 语句中使用数值时,我认为它与一堆 if-else代码>的.
As I found out that I can use only numerical values in C++'s switch statements, I thought that there then must be some deeper difference between it and a bunch of if-else's.
因此我问自己:
- (如何)
switch与if-elseif-elseif在运行速度、编译时间优化和一般编译方面有何不同?我在这里主要说的是 MSVC.
- (How) does
switchdiffer fromif-elseif-elseifin terms of runtime speed, compile time optimization and general compilation? I'm mainly speaking of MSVC here.
推荐答案
一个开关经常被编译成一个跳转表(一个比较来找出要运行的代码),或者如果这不可能,编译器可能仍然对比较重新排序,以便在值之间执行二分搜索(log N 比较).if-else 链是线性搜索(尽管我想,如果所有相关值都是编译时积分常量,编译器原则上可以执行类似的优化).
A switch is often compiled to a jump-table (one comparison to find out which code to run), or if that is not possible, the compiler may still reorder the comparisons, so as to perform a binary search among the values (log N comparisons). An if-else chain is a linear search (although, I suppose, if all the relevant values are compile-time integral constants, the compiler could in principle perform similar optimizations).
这篇关于在 Visual C++ 中 switch 是如何编译的,它的优化和速度如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Visual C++ 中 switch 是如何编译的,它的优化和速
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
