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
}
}
As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large. The primary difference in performance between the two is that the incremental cost of an additional condition is larger for if-else than it is for switch .
A switch statement works much faster than an equivalent if-else ladder. It's because the compiler generates a jump table for a switch during compilation. As a result, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.
Generally if you have a list of very specific values/actions either will do. Switch is likely somewhat faster in most cases due to the ability to create jump tables from the known compile time values.
The first of which is that in most cases, case statements are slightly more efficient than a whole bunch of if statements. However the only real reason why case statements are better that will ever really affect you is that they are a lot easier to read.
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 an isCase
method on the caseExpression object. That call is potentially more expensive than ScriptBytecodeAdapter.compareEqual(left, right)
which is called for an if comparison.
So in Groovy, switch is generally more expensive than serial if blocks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With