case-statement 或 if-statement 效率观点 [英] case-statement or if-statement efficiency perspective

查看:33
本文介绍了case-statement 或 if-statement 效率观点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
是else if"吗?比switch() case"更快?
什么是相对性能差异Java 中的 if/else 与 switch 语句的区别?

我知道case语句可以用跳转表来实现.这是否使它们比 if 语句更有效?

I know that case statements can be implemented with jump tables. Does this make them more efficient than if statements?

这只是应该避免的微优化吗?

Is this just micro-optimization that should be avoided?

推荐答案

我认为最重要的是尽可能清楚地编写代码.像这样的微优化不应该是重点.

例如,如果您有这样的事情:

For example, if you have something like this:

if (age == 10) {
  // ...   
} else if (age == 20) {
  // ...   
} else if (age == 30) {
  // ...   
} else if (age == 40) {
  // ...   
}

那么使用switch语句就更清晰了:

Then it's clearer to use a switch statement:

switch (age) {
    case 10:
        // ...
        break;
    case 20:
        // ...
        break;
    case 30:
        // ...
        break;
    case 40:
        // ...
        break;
}

同样,我将专注于使代码更易于阅读和维护,而不是纳秒级的效率提升.

这篇关于case-statement 或 if-statement 效率观点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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