Sobes.tech
Junior — Middle

Explain the concept of function inlining and its impact on program performance.

sobes.tech AI

Answer from AI

Function inlining is a compiler optimization where a function call is replaced with the body of the function directly at the call site. This eliminates the overhead of a function call (such as jumping and context saving).

In Go, the compiler automatically inlines small functions if it improves performance.

Advantages of inlining:

  • Reduced execution time due to the absence of function calls.
  • Possibility of further optimizations by the compiler (e.g., constant propagation).

Disadvantages:

  • Increased size of the compiled code (code bloat), which can negatively affect caching.

Example:

func add(a, b int) int {
    return a + b
}

func main() {
    sum := add(3, 4) // the compiler may replace the call to add with 3 + 4
    fmt.Println(sum)
}

If the add function is inlined, the call is replaced with the simple expression 3 + 4, which is faster.