Go and vs if-else switch

In Go, switch es are much more flexible than in C (and C ++), since they can handle cases of Boolean expressions and replace large else stairs - if , it would seem, completely, especially by default switch {...} blocks.

 switch { case x < 5 && y > 2: //... case y == 1 || x > 2: //... default: } 

Is there any advantage to using switch over else - if in Go? It seems that increased efficiency will be reduced by the flexibility of the switch . It is only up to the compiler to figure this out and see if it can make a jump table?

Is there any performance advantage when using switch over if and else ?

+6
source share
3 answers

If all of your case are integral constants, you lose the ability to convert switch to a transition table.

So, in the best case, Go switch can be equivalent to C ++ switch if you use only integral constants, but otherwise it will be no more efficient than if/else .

+8
source

It is entirely up to the compiler to understand it and choose a good implementation strategy for your code. You can always find out what code the compiler generates by requesting a listing of the compiler assembly. See the -S option to the Go compiler.

+9
source

This, of course, is not related to the performance of your application. There is probably an even more difficult situation where you can increase productivity. Like saving a single SQL query, probably 1 million if / else / switch.

Don't worry about details like this and focus on higher-level materials.

+2
source

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


All Articles