I know that in Java the switch statement shouldn’t be used when you have few cases, and in this case it’s better use an if else if.
Is it true also for groovy?
Which is more performant between these two code?
myBeans.each{
switch it.name
case 'aValue':
//some operation
case 'anotherValue:
//other operations
}
or:
myBeans.each{
if(it.name == 'aValue'){
//some operation
}
else if (it.name =='anotherValue){
//other operations
}
}
In Java, “switch” is more effient than serial if blocks because the compiler generates a tableswitch instruction where the target can be determined from a jump table.
In Groovy, switch is not restricted to integer values and has a lot of additional semantics, so the compiler cannot use that facility. The compiler generates a series of comparisons, just like it would do for serial if blocks.
However,
ScriptBytecodeAdapter.isCase(switchValue, caseExpression)is called for each comparison. This is always a dynamic method call to anisCasemethod on the caseExpression object. That call is potentially more expensive thanScriptBytecodeAdapter.compareEqual(left, right)which is called for an if comparison.So in Groovy, switch is generally more expensive than serial if blocks.