case-statement或if-statement效率透视图 [英] case-statement or if-statement efficiency perspective

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

问题描述


可能重复:

是否则如果快于switch()案例?

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天全站免登陆