Home >Backend Development >Golang >How to Prevent Function Inlining in Go?

How to Prevent Function Inlining in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 16:50:11449browse

How to Prevent Function Inlining in Go?

Preventing Function Inlining in Go

In Go, the compiler may automatically optimize code performance by inlining functions. However, there may be instances where you want to disable this behavior.

Question:

How can you instruct the Go compiler to not inline a specific function?

Answer:

To prevent inlining for a specific function, use the //go:noinline pragma:

//go:noinline
func isPrime(p int) bool {
    // ...
}

For a global setting to disable all inlining, use the -gcflags=-l flag:

go build -gcflags=-l primes.go

This flag is equivalent to the -O0 optimization level in GCC, which generates unoptimized code without any inlining.

Refer to Dave Cheney's blog post "Mid-stack inlining in Go" for more details on this technique.

The above is the detailed content of How to Prevent Function Inlining in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn