本文介绍了为什么是 switch 语句而不是 if-else?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道这个问题有一段时间了.到目前为止,我不是一个铁杆程序员,主要是小型 Python 脚本,并且我已经编写了几个分子动力学模拟.对于真正的问题:switch 语句 的重点是什么?为什么不能只使用 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 指出这可能是重复的问题 If/Else vs. Switch.如果您想关闭,请这样做.我会留待进一步讨论.

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 更有效.这个想法是在内存中顺序放置一堆跳转指令,然后将值添加到程序计数器中.这用加法操作替换了一系列比较指令.

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

接下来是switch版本:

Next is the switch version:

    // 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:40