15

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?

Grigorii Sokolik
  • 388
  • 1
  • 2
  • 14
  • 4
    Rules for inlining can be found here: [Stimulate code-inlining](https://stackoverflow.com/questions/41119734/stimulate-code-inlining/41119979#41119979). – icza Aug 23 '17 at 10:21
  • There is no manual control over what gets inlined and what not, so: No. – Volker Aug 23 '17 at 10:38
  • @icza there is nothing about loops there isn't it? – Grigorii Sokolik Aug 23 '17 at 10:39
  • I just did a quick test and replacing the for loop with the equivalent labels and goto statements allows inlining, which surprised me as I assumed there was some technical reason for loops couldn't be inlined. – thomasrutter Aug 26 '17 at 12:31

2 Answers2

24

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.

peterSO
  • 158,998
  • 31
  • 281
  • 276
9

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.

NO_GUI
  • 444
  • 8
  • 12