如何开关case语句执行或内部运作的? [英] How Switch case Statement Implemented or works internally?
问题描述
我读的地方,在开关
语句使用二进制搜索或一些排序技术来准确地选择正确的情况下,相比于其他,如果阶梯这增加了它的性能。
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.
推荐答案
它实际上是到编译器开关
语句是如何在code ++实现的。
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".
这篇关于如何开关case语句执行或内部运作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!