如何在使用接口时获得Go的最佳性能?

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

How do you get the maximum performance from Go while using interfaces?

问题

我正在开发一个模拟器,每一条指令都很重要。我们选择使用Go语言是因为它提供了接口抽象的功能,但是通过基准测试发现,通过接口间接调用方法比直接调用方法要慢5倍。然而,我们的项目结构现在依赖于使用接口来解决循环依赖的问题。有没有办法要么提高接口的性能(可能性不大),要么在没有接口的情况下解决循环依赖的问题?

英文:

I'm working on a simulator where every instruction counts. We were drawn to Go because of the interface abstraction, but from benchmarking, it is 5X worse to invoke the indirection of an interface rather than to call a method directly. However, our project structure now relies on the use of interfaces to get around circular dependencies. Is there a way to either make interfaces faster (doubtful) or get around circular dependencies without interfaces?

答案1

得分: 5

如果你遇到循环依赖的问题,那说明你的代码被分成了不同的模块。将所有的代码移到一个单独的模块中。这样你就不需要接口了。在Go语言中,模块通常是相当大的代码组织单元,不要仅仅为了代码组织而创建模块。

英文:

If you're seeing circular dependencies, that suggests you have your code in separate modules. Move all the code into a single module. Then you shouldn't require an interface. Modules are generally quite large groupings in Go. Don't create them just for code organization.

答案2

得分: 2

首先是坏消息,接口的速度现在已经达到了差不多的水平,可能在1.7版本中会有一些改进,但不会太多。

如果你的接口不是很庞大,你可以传递函数而不是接口。

例如:

func Sort(a sort.Interface) // 可以改写为
func Sort(ln int, lessFn func(i, j) bool, swapFn func(i, j))

但我完全同意@RobNapier的观点。

英文:

Well, bad news first, interfaces are about as fast as they are gonna get for now, might be improved a bit by 1.7 but not much.

If your interfaces aren't massive, you can pass funcs around rather than interfaces.

Example:

func Sort(a sort.Interface) // can be rewritten as
func Sort(ln int, lessFn func(i, j) bool, swapFn func(i, j))

But I 100% agree with @RobNapier.

huangapple
  • 本文由 发表于 2016年3月8日 01:31:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/35850167.html
匿名

发表评论

匿名网友

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

确定