嵌套 if 或 switch case 语句
从优化代码运行时间的角度来看,哪里使用“嵌套if”语句以及何时使用“switch case”语句是否有经验法则?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑您是否会找到一个现实生活中的应用程序,其中嵌套 if 和 switch case 之间的差异甚至值得衡量。磁盘访问、Web 访问等需要花费很多数量级的时间。
选择最容易阅读和调试的内容。
另请参阅 IF-ELSE 和 SWITCH 之间有什么区别?< /a> (可能重复)以及 切换 if-else 的优点声明。有趣的是,switch 的支持者写道
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
如果您有超过 2-3 个比较
然后“切换”
否则“如果”
在你去切换策略之前尝试应用一些模式......
If you have more than 2-3 comparisons
then "switch"
else "if"
try to apply some patterns before you go to switch like strategy...
我认为这对于使用任何一种方法实现的决策结构都不会产生任何影响。您的编译器很可能会在可执行文件中生成相同的指令。
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.