Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 793
Ryan Haining Avatar asked May 24 '13 00:05

Ryan Haining


People also ask

Is switch more efficient than if-else?

A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.

Are switch statements faster than if-else in Golang?

A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. This is due to the creation of a jump table for switch during compilation.

Is else if more efficient?

Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE. By using multiple IF-conditions the computer has to go through each and every condition and thus multiple IF-conditions require more time.

Should I use switch or else if?

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch. Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.


1 Answers

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.

like image 118
syam Avatar answered Sep 24 '22 21:09

syam