Advantage of switch over if-else statement

后端 未结 22 2434
梦谈多话
梦谈多话 2020-11-22 11:08

What\'s the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an ex

22条回答
  •  眼角桃花
    2020-11-22 11:46

    switch is definitely preferred. It's easier to look at a switch's list of cases & know for sure what it is doing than to read the long if condition.

    The duplication in the if condition is hard on the eyes. Suppose one of the == was written !=; would you notice? Or if one instance of 'numError' was written 'nmuError', which just happened to compile?

    I'd generally prefer to use polymorphism instead of the switch, but without more details of the context, it's hard to say.

    As for performance, your best bet is to use a profiler to measure the performance of your application in conditions that are similar to what you expect in the wild. Otherwise, you're probably optimizing in the wrong place and in the wrong way.

提交回复
热议问题