3 ms·
Not only that, but despite all of the other syntactic sugar Go is lacking (usually sorely, such as a “try” error handler), the switch statement is really just a
by MrDOS 5y ago
Not only that, but despite all of the other syntactic sugar Go is lacking (usually sorely, such as a “try” error handler), the switch statement is really just an “if” statement in disguise.
var someVar, anotherVar string
// ...
switch {
case someVar == "whatever":
fmt.Println("Tell me how, exactly,")
case anotherVar == "nope":
fmt.Println("this compiles to a jump table?")
default:
fmt.Println("Spoiler: it doesn't.")
}
- acuozzo 5y ago> the switch statement is really just an “if” statement in disguise If the switch is over a fixed set of strings, then can't the backend generate a perfect hash function ala gperf and then proceed to use the computed hash value to implement a jump table? Also, FWIW, the only compiler backends I've ever seen blindly emit a jump table all died in the '80s. Jump tables aren't always the fastest choice: https://www.cipht.net/2017/10/03/are-jump-tables-always-fastest.html https://www.cipht.net/2017/10/03/are-jump-tables-always-fast...
- morelisp 5y agoGo currently uses a binary search for integer switches (and I believe serial comparisons otherwise). Jump tables are in development and likely to appear around 1.19 or 1.20. As you say, there's a lot of edge cases to consider when figuring out whether a table or comparisons are the better choice. https://go-review.googlesource.com/c/go/+/357330/ https://go-review.googlesource.com/c/go/+/357330/
- MrDOS 5y ago> can't the backend (...) implement a jump table? Note that my example “switches” over two independent variables. Even if the Go compiler did generate a table, for this example it would really be generating two tables: and then we're back to the “how is this better than an `if`?” question.