Groovy 'switch' vs. 'if' performance

I know that in Java the switch statement should not be used when you have few cases, in which case it is better to use if else if .

Is this also true for groovy?

What is more efficient between the two codes?

 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 } } 
+7
source share
1 answer

In Java, a "switch" is more efficient than a serial if blocks, because the compiler generates a tableswitch statement where the target can be determined from the jump table.

In Groovy, the switch is not limited to integer values ​​and has a lot of additional semantics, so the compiler cannot use this object. The compiler creates a series of comparisons, exactly the same as for serial blocks.

However, ScriptBytecodeAdapter.isCase(switchValue, caseExpression) is called for each comparison. This is always a dynamic method call for the isCase method of the isCase object. This call is potentially more expensive than ScriptBytecodeAdapter.compareEqual(left, right) , which is called to compare if.

So, in Groovy, a switch is usually more expensive than a serial if blocks.

+13
source

All Articles