去开关串效率

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()
}

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.

  1. in order, all non-constant cases are compiled and tested as if-elses.
  2. groups of larger than 3 constant cases are binary divided and conquered.
  3. 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.