Go: Inlining Strategy & Limitation
Published in
5 min readFeb 9, 2020
ℹ️ This article is based on Go 1.13.
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.
Rules
Let’s start with an example to understand what exactly inlining is. The following program, split into two files, will sum/subtract a list of numbers:
main.gofunc main() {
n := []float32{120.4, -46.7, 32.50, 34.65, -67.45}
fmt.Printf("The total is %.02f\n", sum(n))
}
func sum(s []float32) float32 {
var t float32
for _, v := range s {
if t < 0 {
t = add(t, v)
} else {
t = sub(t, v)
}
}
return t
}op.gofunc add(a, b float32) float32 {
return a + b
}
func sub(a, b float32) float32 {
return a - b
}
Running the program with the flag -gcflags="-m"
shows the inlined functions:
./op.go:3:6: can inline add
./op.go:7:6: can inline sub
./main.go:16:11: inlining call to sub
./main.go:14:11: inlining call to add
./main.go:7:12: inlining call to fmt.Printf