Hello is Go switch string just convenient form, but not fastest possible implementation?
switch s{
case "alpha": doalpha()
case "betta": dobetta()
case "gamma": dogamma()
default: dodefault()
Is this equal to:
if s=="alpha"{
doalpha()
} else if s == "betta" {
dobetta()
} else if s == "gamma" {
dogamma()
} else {
dodefault()
}
The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer.
String is the only non-integer type which can be used in switch statement.
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. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed.
Yes, we can use a switch statement with Strings in Java.
You;d have to benchmark it in order to tell the actual difference for your case. It depends on the compiler and the optimizations it does and thus on platform and architecture.
But see this link from the Go mailing list for some detail on implementation of the switch statement:
what is implemented is as follows.
- in order, all non-constant cases are compiled and tested as if-elses.
- groups of larger than 3 constant cases are binary divided and conquered.
- 3 or fewer cases are compared linearly.
So based on that there should be little if any difference. And the switch statement certainly looks cleaner. And it's the recommend way to write longer if-else statements:
It's therefore possible—and idiomatic—to write an if-else-if-else chain as a switch.
In Go, a constant expression switch
with 4 or more cases is implemented as a binary search.
The cases are sorted at compile time and then binary-searched.
In this small benchmark we can see that a switch
with just 5 cases is on average 1.5 times faster than a corresponding if-then-else sequence. In general we can assume O(logN) vs. O(N) difference in performance.
3 of fewer cases are compared linearly, so expect the same performance as that of if-then-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