Function inlining is a compiler optimization technique where the compiler replaces a function call with the actual body of the function. This can reduce the overhead associated with function calls, such as stack operations and branch predictions, and improve performance, especially for small, frequently called functions.
The Go compiler performs inlining automatically for small functions. You can use the go build -gcflags="-m"
command to see which functions are inlined during the compilation process.
Consider the following example with and without inlining:
gopackage main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
sum := 0
for i := 0; i < 1000000; i++ {
sum = add(sum, i)
}
fmt.Println(sum)
}
The add
function is simple and small, so the compiler can inline it:
gopackage main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
sum := 0
for i := 0; i < 1000000; i++ {
// Inlined: sum = sum + i
sum += i
}
fmt.Println(sum)
}
In this example, the function call to add
might be inlined by the compiler, resulting in:
gofunc main() {
sum := 0
for i := 0; i < 1000000; i++ {
sum = sum + i
}
fmt.Println(sum)
}
-gcflags="-m"
to Inspect InliningYou can check which functions are inlined by the compiler using the -gcflags="-m"
flag:
shellgo build -gcflags="-m" main.go
This will output messages indicating which functions were inlined:
shell# command-line-arguments
./main.go:5:6: can inline add
./main.go:10:11: inlining call to add
Function inlining is a powerful optimization technique that can significantly reduce function call overhead and improve performance. In Go, the compiler automatically inlines suitable functions, but understanding how inlining works and knowing how to inspect and guide the compiler can help you write more efficient code. By keeping functions small and frequently called functions simple, you can leverage inlining to enhance the performance of your Go applications.