Ryan Haining
Ryan Haining

Reputation: 36882

Go switch vs if-else efficiency

In Go, switches are much more flexible than in C (and C++) since they can handle cases of boolean expressions and replace large else-if ladders seemingly entirely, especially with the default switch {...} blocks.

switch {
    case x < 5 && y > 2:
        //...
    case y == 1 || x > 2:
        //...
    default:
}

Is there any efficiency advantage to using a switch over else-if in Go? It seems that the boosted efficiency would be lost by the switch's flexibility. Is it just up to the compiler to figure it out and see if it can make a jump table?

Is there any performance advantage to using switch over if and else?

Upvotes: 18

Views: 16388

Answers (3)

syam
syam

Reputation: 15089

Unless all your case are integral constants then you lose the possibility of transforming the switch to a jump-table.

So, at best, Go's switch might be equivalent to C++'s switch if you only use integral constants, but otherwise it will be no more efficient than if/else.

Upvotes: 19

Zyo
Zyo

Reputation: 2068

It's surely irrelevant for your application performance. There is probably other more complex situation where you can improve performance. Like saving a single SQL query is probably like 1 million if/else/switch.

Do not worry much about detail like that and focus on higher level stuff.

Upvotes: 6

Greg Hewgill
Greg Hewgill

Reputation: 994261

It's completely up to the compiler to figure it out and choose a good implementation strategy for your code. You can always find out what code the compiler is generating by requesting an assembly listing of the compiler output. See the -S option to the Go compiler.

Upvotes: 15

Related Questions