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 语句如何在内部实现或工作?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01