Advantage of switch over if-else statement

后端 未结 22 2147
梦谈多话
梦谈多话 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 12:01
    while (true) != while (loop)
    

    Probably the first one is optimised by the compiler, that would explain why the second loop is slower when increasing loop count.

    0 讨论(0)
  • 2020-11-22 12:01

    Seeing as you only have 30 error codes, code up your own jump table, then you make all optimisation choices yourself (jump will always be quickest), rather than hope the compiler will do the right thing. It also makes the code very small (apart from the static declaration of the jump table). It also has the side benefit that with a debugger you can modify the behaviour at runtime should you so need, just by poking the table data directly.

    0 讨论(0)
  • 2020-11-22 12:03

    If your cases are likely to remain grouped in the future--if more than one case corresponds to one result--the switch may prove to be easier to read and maintain.

    0 讨论(0)
  • 2020-11-22 12:06

    I agree with the compacity of the switch solution but IMO you're hijacking the switch here.
    The purpose of the switch is to have different handling depending on the value.
    If you had to explain your algo in pseudo-code, you'd use an if because, semantically, that's what it is: if whatever_error do this...
    So unless you intend someday to change your code to have specific code for each error, I would use if.

    0 讨论(0)
提交回复
热议问题