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

前端 未结 20 1129
时光取名叫无心
时光取名叫无心 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:26

    Interest question. This came up a few weeks ago at work and we found an answer by writing an example snippet and viewing it in .NET Reflector (reflector is awesome!! i love it).

    This is what we discovered: A valid switch statement for anything other than a string gets compiled to IL as a switch statement. However IF it is a string it is rewritten as a if/else if/else in IL. So in our case we wanted to know how switch statements compare strings e.g is case-sensitive etc. and reflector quickly gave us an answer. This was useful to know.

    If you want to do case-sensitive compare on strings then you could use a switch statement as it is faster than performing a String.Compare in an if/else. (Edit: Read What is quicker, switch on string or elseif on type? for some actual performance tests) However if you wanted to do a case-insensitive then it is better using a if/else as the resulting code is not pretty.

    switch (myString.ToLower())
    {
      // not a good solution
    }
    

    The best rule of thumb is to use switch statements if it makes sense (seriously), e.g:

    • it improves the readability of your code
    • you are comparing a range of values (float, int) or an enum

    If you need to manipulate the value to feed into the switch statement (create a temporary variable to switch against) then you probably should be using an if/else control statement.

    An update:

    It is actually better to convert the string to uppercase (e.g. ToUpper()) as that has been apparently there are further optimizations that the just-in-time compiler can do as when compared to the ToLower(). It is a micro optimization, however in a tight loop it could be useful.


    A little side note:

    To improve the readability of switch statements try the following:

    • put the most likely branch first i.e. most accessed
    • if they are all likely to occur, list them in alphabetical order so it is easier to find them.
    • never use the default catch-all for the last remaining condition, that's lazy and will cause issues later on in the code's life.
    • use the default catch-all to assert an unknown condition even though it highly unlikely it will ever occur. that is what asserts are good for.

提交回复
热议问题