Is there any significant difference between using if/else and switch-case in C#?

前端 未结 20 1109
时光取名叫无心
时光取名叫无心 2020-11-22 07:25

What is the benefit/downside to using a switch statement vs. an if/else in C#. I can\'t imagine there being that big of a difference, other than m

20条回答
  •  一整个雨季
    2020-11-22 07:46

    Not just C#, but all C-based languages, I think: because a switch is limited to constants, it's possible to generate very efficient code using a "jump table". The C case is really a good old FORTRAN computed GOTO, but the C# case is still tests against a constant.

    It is not the case that the optimizer will be able to make the same code. Consider, eg,

    if(a == 3){ //...
    } else if (a == 5 || a == 7){ //...
    } else {//...
    }
    

    Because those are compound booleans, the generated code has to compute a value, and shortcircuit. Now consider the equivalent

    switch(a){
       case 3: // ...
        break;
       case 5:
       case 7: //...
        break;
       default: //...
    }
    

    This can be compiled into

    BTABL: *
    B3:   addr of 3 code
    B5:
    B7:   addr of 5,7 code
          load 0,1 ino reg X based on value
          jump indirect through BTABL+x
    

    because you are implicitly telling the compiler that it doesn't need to compute the OR and equality tests.

提交回复
热议问题