在Go语言中使用通道对性能有好处吗?

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

Is using channels in Go good for performance?

问题

我想知道通道是否足够高效,可以作为编写Go程序的一部分。

英文:

I'm wondering as to whether channels are efficient enough to be used as part of coding a Go program.

答案1

得分: 9

在Go语言中,通道不是一个函数,而是一种原始类型,被称为语言的一等公民。

与信号量(互斥锁)相比,通道是高度推荐的,因为当正确使用时,它们可以非常高效地序列化并发访问。

Go语言肯定比任何解释型动态语言表现更好,并且在处理并发方面比许多编译型语言更出色。虽然在火箭控制器等特定用例中,Go语言可能不太适合,但对于普通的真实世界应用程序来说,Go语言肯定是最快和最灵活的语言之一。

英文:

Channels in Go are not a function, they are a primitive type, a so called first-class citizen of the language.

In contrast to semaphores (aka. mutexes), channels are highly recommended since, when used correctly, they can serialize concurrent access very efficiently.

Go will certainly outperform any interpreted dynamic language and deals with concurrency way better than a lot of compiled languages. There are still a couple of use-cases where Go is not adequate, like in rocket controllers and the like but for normal real-world applications, Go is certainly one of the fastest and most flexible languages around.

答案2

得分: 5

一般来说,是的,通道是快速的,但是我们无法确定在不了解您的程序的情况下是否应该使用它。我认为这部分内容没有建设性。

至于实现,当您安装带有源代码的Go时,它是可用的。例如,在src/pkg/runtime/chan.c中查找。

大多数Go并发程序依赖于通道。如果您想在Go中编写并执行并发任务,我认为您几乎没有选择:使用通道,进行性能分析,并查看是否存在与通道相关的问题。

英文:

Generally speaking, yes, channels are fast but we can't tell if you should use it without knowing your program. I'd say this part isn't constructive.

As for the implementation, it's available when you install Go with the sources. Look for exemple at src/pkg/runtime/chan.c.

Most Go concurrent programs rely on channels. If you want to code in Go and execute concurrent tasks, I'd say you have almost no choice : use channels, profile, and see if you have a problem related to channels.

答案3

得分: 0

你的问题有点奇怪,因为显然很多Go程序确实有效地使用了通道,所以答案绝对是肯定的。但我想你可能是指:通道对于我的使用情况是否足够高效。如果你能详细说明一下你的程序应该做什么,那么我可以给你一个更好的答案。

值得一提的是,我使用Go编写了许多高性能的程序,这些程序需要大量(从几十到几百个)通道在相似数量的goroutine之间进行通信。所以总的来说,它们相当高效。

英文:

Your question is odd, because obviously many Go programs do use channels efficiently so the answer is absolutely yes. But I think you may mean: Are channels efficient enough for my use case. If you can elaborate a bit more on what your program is supposed to do, then I can give you a better answer.

For what it's worth, I've used Go to write lots of highly performant programs that require lots and lots (from dozens to hundreds) of channels communicating across a similar number of goroutines. So yeah, they're pretty efficient in general.

huangapple
  • 本文由 发表于 2012年9月24日 11:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/12558637.html
匿名

发表评论

匿名网友

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

确定