英文:
Go switch string efficiency
问题
你好,Go语言中的switch语句只是一种方便的形式,但不一定是最快的实现方式。
以下是你提供的代码的翻译:
switch s{
case "alpha": doalpha()
case "betta": dobetta()
case "gamma": dogamma()
default: dodefault()
}
这段代码等同于:
if s=="alpha"{
doalpha()
} else if s == "betta" {
dobetta()
} else if s == "gamma" {
dogamma()
} else {
dodefault()
}
希望对你有帮助!如果还有其他问题,请随时提问。
英文:
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()
}
答案1
得分: 15
你需要对其进行基准测试,以确定在你的情况下实际的差异。这取决于编译器以及它所进行的优化,因此也取决于平台和架构。
但是,可以参考Go邮件列表中关于switch语句实现的链接,了解一些详细信息:
> 实现如下。
>
> 1. 按顺序,所有非常量的情况都被编译并测试为if-else。
> 2. 大于3个常量情况的组被二分并征服。
> 3. 3个或更少的情况进行线性比较。
因此,基于这一点,应该几乎没有任何差异。而且switch语句看起来更清晰。这也是编写较长的if-else语句的推荐方式:
> 因此,将if-else-if-else链写成switch是可能的,也是惯用的方式。
英文:
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.
答案2
得分: 4
在Go语言中,具有4个或更多case的常量表达式switch
被实现为二分查找。
这些case在编译时进行排序,然后进行二分查找。
在这个小型基准测试中,我们可以看到,只有5个case的switch
平均比相应的if-then-else序列快1.5倍。一般情况下,我们可以假设性能上的O(logN)与O(N)的差异。
对于3个或更少的case,将进行线性比较,因此可以期望与if-then-else相同的性能。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论