Inlining
- Go course
- Expert
- Lesson 16/34
- 4 min
Learn how the compiler inlines functions.
Inlining
Inlining replaces a call to a small function with its body; the call overhead disappears and more optimizations open up in the caller. The Go compiler gives each function a cost; those under the budget (80 nodes) are inlined.
func kare(x int) int { return x * x }
y := kare(5) // after compiling: y := 5 * 5 → 25The -gcflags=-m output shows the lines can inline kare and inlining call to kare.
Mid-stack inlining and PGO
Since Go 1.12, functions that call other functions (mid-stack) can also be inlined. Functions with loops, defer, recover or a large switch may exceed the cost. For calls marked "hot" in a PGO profile the budget is raised, so the most-run paths are optimized more aggressively.
Practice Effect of noinline
Write topla(a, b int) int and toplaNI(a, b int) int marked //go:noinline. Measure both with testing.Benchmark and print whether both results ran more than 0 iterations (N > 0).
Starter code
package main
import (
"fmt"
"testing"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"testing"
)
var sink int
func topla(a, b int) int { return a + b }
//go:noinline
func toplaNI(a, b int) int { return a + b }
func main() {
r1 := testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = topla(i, 1)
}
})
r2 := testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ {
sink = toplaNI(i, 1)
}
})
fmt.Println(r1.N > 0 && r2.N > 0)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which directive prevents a function from being inlined?
- //go:noinline Correct answer
- //go:inline
- //go:nosplit
- //go:embed
Explanation: //go:noinline is usually used in benchmarks and tests to measure real call cost; Go has no //go:inline directive.
2 Disable inlining
go build -gcflags=____ .
go build -gcflags=-l .
Explanation: -gcflags=-l turns off all inlining; it is used for debugging and comparisons.
3 Flag and meaning
| Term | Meaning |
|---|---|
-gcflags=-m |
Show decisions |
-gcflags=-l |
Inlining off |
-gcflags=-N |
Optimizations off |
//go:noinline |
Block one function |