如果嵌套或​​交换机case语句 [英] Nested if or switch case statement

查看:159
本文介绍了如果嵌套或​​交换机case语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从视图优化code运行时的角度来看,是有什么地方使用嵌套if语句,以及何时使用开关的情况下的语句拇指规则?

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 ?

推荐答案

我怀疑你会找到一个现实生活中的应用程序,其中一个嵌套如果和一个开关外壳之间的差异就值得测量。磁盘访问,网络访问等采取的大小更多的时间很多很多的订单。

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.

另请参阅<一个href=\"http://stackoverflow.com/questions/680656/what-is-the-difference-between-if-else-and-switch\">What 如果VS之间的IF-ELSE和切换?(可能重​​复)的差异,以及-else 。有趣的是,开关的支持者写道:

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

在最坏的情况下,编译器将
  产生相同的code作为的if-else
  链,这样你就不会失去任何东西。如果
  疑问把最常见的情况下,
  首先进入switch语句。

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.

在优化程序可能最好的情况
  找到更好的方法来生成
  code。编译器不常见的东西是
  建立一个二进制decission树
  (保存进行比较,并在跳跃
  一般情况下)或者干脆建一个
  跳表(工程没有比较时
  所有)。

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).

这篇关于如果嵌套或​​交换机case语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆