Switch case 语句如何在内部实现或工作?

2021-12-12 00:00:00 gcc c if-statement switch-statement c++

我在某处读到 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".

相关文章