英文:
Go switch vs if-else efficiency
问题
在Go语言中,switch
语句比C语言(和C++)中的switch
语句更加灵活,因为它们可以处理布尔表达式的情况,并且可以完全替代大型的else
-if
梯子,特别是使用默认的switch {...}
块。
在Go语言中,使用switch
语句是否有任何效率优势?似乎switch
语句的灵活性会导致提升的效率丧失。这是否只取决于编译器来判断并查看是否可以生成跳转表?
在使用switch
语句与使用if
和else
语句相比,是否有性能优势?
英文:
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
-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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论