Inlining functions in Go

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

Inlining functions in Go

问题

Go语言使用通用的sort.Interface实现了一个很好的introsort。但是C++的std::sort的一个优点是可以指定一个内联的比较函数,并且可以省略不必要的函数调用。
我们能否通过某种方式强制当前的原生Go编译器内联这些sort.Swapsort.Less调用?我不考虑使用gccgo,因为与原生编译器相比,它给我们带来了糟糕的结果。

英文:

Go has a nice generic implementation of introsort using the generic sort.Interface. But one of the advantages of C++'s std::sort is that you can specify a compare functor which is inlined and unnecessary function calls are omitted.
Can we force the current native Go compilers somehow to inline those sort.Swap and sort.Less calls? I do not consider gccgo because it gives us terrible results compared to the native compiler.

答案1

得分: 3

对于Go 1.x版本来说,答案是否定的。

Go编译器可能会在某些特定平台上以某些特定方式内联一些函数类别。你甚至可能能够通过某些手段让当前的编译器在你的架构上内联sort-"functor",但绝对不能保证这在未来的版本中仍然有效,而且这可能会对你产生负面影响(甚至破坏你的代码,取决于所涉及的技巧水平)当编译器发生变化时。

Go的一个重大发布版本(2.x?)可能会对优化提供一些保证;但对于Go 1.x来说,并没有类似的保证。而且,即使Go的作者想要这样做,为所有平台提供这样的保证也很困难(请记住,Go可以在许多架构上运行)。

更一般地说,在任何语言中依赖于编译器特定行为都是一个坏主意。

英文:

For Go 1.x the answer is a sound no.

The Go compiler may inline some classes of functions on some platforms in some specific ways. You might even be able to figure out some trickery through which you can make the current compiler inline the sort-"functor" on your architecture but there is absolutely no guarantee whatsoever that this will hold in future releases and it may work against you (even break your code, depending on the level of hackery involved) when the compiler changes.

A major release of Go (2.x?) might provide some guarantees about optimizations; but for Go 1.x there's nothing like that. And even if the Go authors wanted to do this it's difficult to provide such guarantees for all platforms (remember Go runs on many architectures).

Even more generally it is a bad idea to rely on compiler-specific behavior, in any language.

huangapple
  • 本文由 发表于 2014年10月12日 17:21:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/26323611.html
匿名

发表评论

匿名网友

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

确定