Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go switch string efficiency

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()
}
like image 743
ash Avatar asked Apr 10 '15 16:04

ash


People also ask

Are switch statements faster than if else in Golang?

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.

Can you use switch statements with strings C#?

String is the only non-integer type which can be used in switch statement.

Are switch cases faster than if else?

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.

Can switch be used with strings?

Yes, we can use a switch statement with Strings in Java.


2 Answers

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.

like image 28
IamNaN Avatar answered Nov 07 '22 14:11

IamNaN


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.

like image 179
rustyx Avatar answered Nov 07 '22 15:11

rustyx