8

我知道在 Java 中,当你有少数情况时不应该使用switchif else if语句,在这种情况下最好使用.

groovy 也是如此吗?

这两个代码之间哪个性能更高?

myBeans.each{
    switch it.name
    case 'aValue':
        //some operation
    case 'anotherValue:
        //other operations
}

或者:

myBeans.each{
    if(it.name == 'aValue'){
        //some operation
    }
    else if (it.name =='anotherValue){
        //other operations
    }
}
4

1 回答 1

14

在 Java 中,“switch”比串行 if 块更有效,因为编译器会生成一个tableswitch指令,其中可以从跳转表中确定目标。

在 Groovy 中,switch 不限于整数值,并且具有许多附加语义,因此编译器无法使用该功能。编译器会生成一系列比较,就像它对串行 if 块所做的那样。

但是,ScriptBytecodeAdapter.isCase(switchValue, caseExpression)每次比较都会调用。这始终是isCase对 caseExpression 对象上的方法的动态方法调用。该调用可能比ScriptBytecodeAdapter.compareEqual(left, right)if 比较调用的调用更昂贵。

所以在 Groovy 中,switch 通常比串行 if 块更昂贵。

于 2012-08-24T17:50:05.913 回答