Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy 'switch' vs. 'if' performance

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
    }
}
like image 900
rascio Avatar asked Aug 24 '12 15:08

rascio


People also ask

Are switches faster than if statements?

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 .

Why is switch faster than if-else?

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.

In what circumstance is it better to use a switch statement over an If statement?

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.

Is a case statement more efficient than if?

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.


1 Answers

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.

like image 96
Ingo Kegel Avatar answered Oct 07 '22 17:10

Ingo Kegel