Go开关语句与if-else语句的效率比较

huangapple go评论128阅读模式
英文:

Go switch vs if-else efficiency

问题

在Go语言中,switch语句比C语言(和C++)中的switch语句更加灵活,因为它们可以处理布尔表达式的情况,并且可以完全替代大型的else-if梯子,特别是使用默认的switch {...}块。

在Go语言中,使用switch语句是否有任何效率优势?似乎switch语句的灵活性会导致提升的效率丧失。这是否只取决于编译器来判断并查看是否可以生成跳转表?

在使用switch语句与使用ifelse语句相比,是否有性能优势?

英文:

In Go, switches are much more flexible than in C (and C++) since they can handle cases of boolean expressions and replace large else-if ladders seemingly entirely, especially with the default switch {...} blocks.

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

Is there any efficiency advantage to using a switch over else-if in Go? It seems that the boosted efficiency would be lost by the switch's flexibility. Is it just up to the compiler to figure it out and see if it can make a jump table?

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

答案1

得分: 17

除非你的所有case都是整数常量,否则你就失去了将switch转换为跳转表的可能性。

因此,最好的情况是,如果你只使用整数常量,Go的switch可能与C++的switch等效,但否则它将不比if/else更高效。

英文:

Unless all your case are integral constants then you lose the possibility of transforming the switch to a jump-table.

So, at best, Go's switch might be equivalent to C++'s switch if you only use integral constants, but otherwise it will be no more efficient than if/else.

答案2

得分: 13

完全由编译器来解决并选择一个好的代码实现策略。您可以通过请求编译器输出的汇编清单来了解编译器生成的代码。请参阅Go编译器的-S选项

英文:

It's completely up to the compiler to figure it out and choose a good implementation strategy for your code. You can always find out what code the compiler is generating by requesting an assembly listing of the compiler output. See the -S option to the Go compiler.

答案3

得分: 3

这对你的应用程序性能来说肯定是无关紧要的。可能还有其他更复杂的情况可以提高性能。像保存一个单独的SQL查询可能相当于100万个if/else/switch语句。

不要过多担心这样的细节,专注于更高层次的事情。

英文:

It's surely irrelevant for your application performance. There is probably other more complex situation where you can improve performance. Like saving a single SQL query is probably like 1 million if/else/switch.

Do not worry much about detail like that and focus on higher level stuff.

huangapple
  • 本文由 发表于 2013年5月24日 08:14:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/16725921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定