英文:
Is it possible to inline function, containing loop in Golang?
问题
例如,我有以下的golang测试代码:
// inline-tests.go
package inlinetests
func plus(a, b int) int {
return a + b
}
func plus_plus(a, b, c int) int {
return plus(plus(a, b), plus(b, c))
}
func plus_iter(l ...int) (res int) {
for _, v := range l {
res += v
}
return
}
如果我尝试构建它,我会收到以下信息:
go build -gcflags=-m inline-tests.go
# command-line-arguments
./inline-tests.go:4: can inline plus
./inline-tests.go:8: can inline plus_plus
./inline-tests.go:9: inlining call to plus
./inline-tests.go:9: inlining call to plus
./inline-tests.go:9: inlining call to plus
./inline-tests.go:12: plus_iter l does not escape
有没有办法让编译器内联 plus_iter
函数?如果有,有没有办法内联映射迭代?
英文:
For instance, I have the following test in golang:
// inline-tests.go
package inlinetests
func plus(a, b int) int {
return a + b
}
func plus_plus(a, b, c int) int {
return plus(plus(a, b), plus(b, c))
}
func plus_iter(l ...int) (res int) {
for _, v := range l {
res += v
}
return
}
If I try to build it, I receive the following:
go build -gcflags=-m inline-tests.go
# command-line-arguments
./inline-tests.go:4: can inline plus
./inline-tests.go:8: can inline plus_plus
./inline-tests.go:9: inlining call to plus
./inline-tests.go:9: inlining call to plus
./inline-tests.go:9: inlining call to plus
./inline-tests.go:12: plus_iter l does not escape
Is there any way to let compiler inline plus_iter
? If yes, is there any way to inline map iteration?
答案1
得分: 24
> Go Wiki
>
> 编译器优化
>
> 函数内联
>
> 只有短小简单的函数才会被内联。要进行内联,函数必须包含的表达式少于约40个,并且不包含复杂的内容,如函数调用、循环、标签、闭包、panic、recover、select、switch等。
目前,带有循环的函数不会被内联。
英文:
> Go Wiki
>
> CompilerOptimizations
>
> Function Inlining
>
> Only short and simple functions are inlined. To be inlined a function
> must contain less than ~40 expressions and does not contain complex
> things like function calls, loops, labels, closures, panic's,
> recover's, select's, switch'es, etc.
Currently, functions with loops are not inlined.
答案2
得分: 8
截至Go版本1.16:
https://golang.org/doc/go1.16#compiler
编译器现在可以内联具有非标记的for循环、方法值和类型切换的函数。内联器还可以检测更多可能进行内联的间接调用。
英文:
As of go version 1.16:
https://golang.org/doc/go1.16#compiler
> The compiler can now inline functions with non-labeled for loops, method values, and type switches. The inliner can also detect more indirect calls where inlining is possible.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论