Go Switch Column Efficiency

Hi - Go switch string, just a convenient form, but not the fastest 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() } 
+7
source share
2 answers

You must compare it to determine the real difference for your case. It depends on the compiler and the optimizations it performs, and therefore on the platform and architecture.

But look at this link from the Go mailing list for some details on the implementation of the switch statement:

which is implemented as follows.

  1. in order, all mutable cases are compiled and checked as if-elses.
  2. groups of more than 3 constants are divided into binary and conquered.
  3. 3 or fewer cases are compared linearly.

Therefore, based on this, there should be few differences. And the switch statement certainly looks cleaner. And this is the recommended way to write longer if-else statements:

Therefore, it is possible - and idiomatically - to write an if-else-if-else chain as a switch.

+12
source

In Go switch constant expression with 4 or more cases is implemented as a binary search .

Cases are sorted at compile time, and then binary search.

In this small test, we see that a switch with only 5 cases is on average 1.5 times faster than the corresponding if-then-else sequence. In general, we can assume the difference in O (logN) and O (N) in performance.

3 out of fewer cases are compared linearly, so expect the same performance as if-then-else.

0
source

Source: https://habr.com/ru/post/984958/


All Articles