嵌套if else和switch之间的内部工作差异 [英] the internal working difference between nested if else and switch

查看:152
本文介绍了嵌套if else和switch之间的内部工作差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嵌套if else和switch的情况都生成相同的输出。内部如何工作?搜索机制是不同的还是相同的,哪一个是有效的?

Both nested if else and switch case generate the same output.How internally both work?The search mechanism is it different or same and which one of these is efficient?

推荐答案

switch语句的想法是做一个计算分支。在理想情况下,switch语句可以编译成几个指令和一个分支表;每个案例都需要一段时间,而不是线性时间,如果是elseif,那么这是一个很长的构造。



不幸的是,案例值有时会分散在不允许创建分支表的值范围,或者至少是空间禁止的值。在这种情况下,一个好的编译器会生成代码,这些代码是几个不同的分支表和一些传统的if elseif代码的组合。所以在最坏的情况下,switch语句甚至可能比相应的if ifif慢。



编译器开发人员已经发明了相当多的技巧来映射甚至广泛分布的分支将值转换为有效的代码。



所以我的想法是,如果你有许多分支目标,那么使用switch语句,它将比相应的if elseif结构更有效,假设案例值属于紧凑区间。
The idea of the switch statement is to do a computed branch. In the ideal case a switch statement can be compiled into just a few instructions and a branch table; it takes constant time for every of the cases instead of linear time for a lengthy if elseif elseif ... construct.

Unfortunately, the case values are sometimes spread over a range of values that would not allow the creation of a branch table or would at least be space prohibitive. In such cases a good compiler generates code that is a combination of several distinct branch tables and some conventional "if elseif" code. So in the worst case, a switch statement could even be slower than the corresponding if elseif.

Compiler developers have invented quite a few more tricks to map even widely distributed branch values into effivient code.

So the idea is, if you have many branch targets then use a switch statement and it will be much more efficient than the corresponding if elseif construct, given that the case values fall into a compact interval.


这篇关于嵌套if else和switch之间的内部工作差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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