问题描述
我一直想知道这件事已经有一段时间了。我到目前为止还不是一个核心程序员,主要是小型Python脚本,我写了几个分子动力学模拟。对于真正的问题: 开关语句 有什么意义?为什么你不能只使用 if-else语句 ?
I've been wondering this for some time now. I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations. For the real question: What is the point of the switch statement? Why can't you just use the if-else statement?
感谢您的回答,如果有的话之前被问过请指点链接。
Thanks for your answer and if this has been asked before please point me to the link.
编辑
指出这可能是问题的重复。如果你想关闭,那么这样做。我将把它留待进一步讨论。
S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch. If you want to close then do so. I'll leave it open for further discussion.
推荐答案
switch 构造更容易翻译成。当case标签靠近时,这可以使switch语句比 if-else 更有效。我们的想法是在内存中依次放置一堆跳转指令,然后将值添加到程序计数器中。这将使用add操作替换一系列比较指令。
A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation.
下面是一些非常简化的伪装配示例。首先,if-else版本:
Below are some extremely simplified psuedo-assembly examples. First, the if-else version:
// C version
if (1 == value)
function1();
else if (2 == value)
function2();
else if (3 == value)
function3();
// assembly version
compare value, 1
jump if zero label1
compare value, 2
jump if zero label2
compare value, 3
jump if zero label3
label1:
call function1
label2:
call function2
label3:
call function3
接下来是开关版本:
// C version
switch (value) {
case 1: function1(); break;
case 2: function2(); break;
case 3: function3(); break;
}
// assembly version
add program_counter, value
call function1
call function2
call function3
您可以看到生成的汇编代码更加紧凑。请注意,需要以某种方式转换该值以处理除1,2和3之外的其他值。但是,这应该说明这个概念。
You can see that the resulting assembly code is much more compact. Note that the value would need to be transformed in some way to handle other values than 1, 2 and 3. However, this should illustrate the concept.
这篇关于为什么switch语句而不是if-else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!