ras*_*cio 7 performance groovy switch-statement
我知道在Java中,当你的情况很少时,不应该使用switch语句,在这种情况下,最好使用一个if else if.
对于groovy来说也是如此吗?
哪个在这两个代码之间更高效?
myBeans.each{
switch it.name
case 'aValue':
//some operation
case 'anotherValue:
//other operations
}
Run Code Online (Sandbox Code Playgroud)
要么:
myBeans.each{
if(it.name == 'aValue'){
//some operation
}
else if (it.name =='anotherValue){
//other operations
}
}
Run Code Online (Sandbox Code Playgroud)
Ing*_*gel 13
在Java中,"switch"比块if if块更有效,因为编译器生成一个tableswitch指令,其中目标可以从跳转表中确定.
在Groovy中,switch不限于整数值,并且具有许多额外的语义,因此编译器不能使用该工具.编译器生成一系列比较,就像它对serial if块一样.
但是,ScriptBytecodeAdapter.isCase(switchValue, caseExpression)每次比较都需要调用.这始终是isCase对caseExpression对象上的方法的动态方法调用.该调用可能比ScriptBytecodeAdapter.compareEqual(left, right)if 调用更昂贵.
所以在Groovy中,如果是块,交换机通常比串行更昂贵.
| 归档时间: |
|
| 查看次数: |
3189 次 |
| 最近记录: |