Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inline function, containing loop in Golang?

Tags:

performance

go

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?

like image 298
Grigorii Sokolik Avatar asked Aug 23 '17 10:08

Grigorii Sokolik


People also ask

Can inline functions have loops?

A function with loops can be made inline, But every time a function is called, there is a certain amount of performance overhead that occurs.

What should we not use while making a function inline?

We should not use functions that are I/O bound as inline functions. When large code is used in some function, then we should avoid the inline. When recursion is used, inline function may not work properly.

Does Golang inline function?

The inlining process replaces a function call by the body of this function. Although this optimization increases the binary size, it improves the performance of the programs. However, Go does not inline all the functions and follows some rules.

Why is inline faster?

inline functions might make it faster: As shown above, procedural integration might remove a bunch of unnecessary instructions, which might make things run faster. inline functions might make it slower: Too much inlining might cause code bloat, which might cause “thrashing” on demand-paged virtual-memory systems.


1 Answers

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.

like image 173
NO_GUI Avatar answered Oct 04 '22 13:10

NO_GUI