How Switch case Statement Implemented or works internally?(Switch case 语句如何在内部实现或工作?)
问题描述
我在某处读到 switch 语句使用二进制搜索"或一些排序技术来准确选择正确的案例,与 else-if 阶梯相比,这提高了它的性能.
I read somewhere that the switch statement uses "Binary Search" or some sorting techniques to exactly choose the correct case and this increases its performance compared to else-if ladder.
而且,如果我们按顺序给出案例,开关是否工作得更快?是这样吗?您能否就此提出宝贵的建议?
And also if we give the case in order does the switch work faster? is it so? Can you add your valuable suggestions on this?
我们在此处讨论了相同的问题,并计划作为问题发布.
We discussed here about the same and planned to post as a question.
推荐答案
如何在代码中实现 switch 语句实际上取决于编译器.
It's actually up to the compiler how a switch statement is realized in code.
不过,我的理解是,在合适的时候(也就是比较密集的情况),使用跳转表.
However, my understanding is that when it's suitable (that is, relatively dense cases), a jump table is used.
这意味着:
switch(i) {
case 0: doZero(); break;
case 1: doOne();
case 2: doTwo(); break;
default: doDefault();
}
最终会被编译成类似(可怕的伪汇编程序,但我希望它应该很清楚).
Would end up getting compiled to something like (horrible pseudo-assembler, but it should be clear, I hope).
load i into REG
compare REG to 2
if greater, jmp to DEFAULT
compare REG to 0
if less jmp to DEFAULT
jmp to table[REG]
data table
ZERO
ONE
TWO
end data
ZERO: call doZero
jmp END
ONE: call doOne
TWO: call doTwo
jmp END
DEFAULT: call doDefault
END:
如果不是这样,还有其他可能的实现方式允许在某种程度上比一系列条件更好".
If that's not the case, there are other possible implementations that allow for some extent of "better than a a sequence of conditionals".
这篇关于Switch case 语句如何在内部实现或工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Switch case 语句如何在内部实现或工作?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
