In Go, switch
es 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
?
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.
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.
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.
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.
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
.
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