Nested if or switch case statement

痴心易碎 提交于 2019-12-13 04:21:41

问题


From the point of view of optimizing the code run time, is there a thumb rule for where to use "nested if" statement and when to use "switch case" statements ?


回答1:


I doubt you will ever find a real-life application where the difference between a nested if and a switch case is even worth measuring. Disk access, web access, etc. take many many orders of magnitude more time.

Choose what is easiest to read and debug.

Also see What is the difference between IF-ELSE and SWITCH? (possible duplicate) as well as Advantage of switch over if-else statement. Interestingly, a proponent of switch writes

In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.

In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decission tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).




回答2:


If you have more than 2-3 comparisons then "switch" else "if"

try to apply some patterns before you go to switch like strategy...




回答3:


I don't believe it will make any difference for a decision structure that could be implemented using either method. It's highly likely that your compiler would produce the same instructions in the executable.



来源:https://stackoverflow.com/questions/6211725/nested-if-or-switch-case-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!