# 8.1 简介

函数调用的上下文切换存在固定的额外开销，如果程序中存在大量的函数调用，则势必会影响程序的执行性能。而上下文切换的开销是基本固定的，所以相对于函数的总体执行开销，小函数上下文切换所占的比重更大。因此减少程序中的小函数调用，是优化程序性能的重要方向。

Inline(内联)便是这样的一种技术，其用函数体替换掉函数调用，例如如下代码：

```go
func sum(base, i int) int {
    return 100/base + i
}

func doSum(base int, ints []int) int {
    var s int
    for _, val := range ints {
        s += sum(base, val)
    }

    return s
}
```

Inline 之后代码为：

```go
func doSum(base int, ints []int) int {
    var s int
    for _, val := range ints {
        s += 100/base + val
    }

    return s
}
```

这样我们就去掉了所有对函数 `sum` 的调用。不仅如此，编译器还可以对 Inline 之后的代码做进一步的优化，例如上述代码中， `100/base` 在每次循环中都不会改变，因此编译器可以引入一个局部变量做进一步优化：

```go
func doSum(base int, ints []int) int {
    var s int
    baseTemp := 100 / base
    for _, val := range ints {
        s += baseTemp + val
    }

    return s
}
```

这样 `100/base` 只需要计算一次，而不用在每个 for 循环体内重复计算。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gocompiler.shizhz.me/8.-golang-bian-yi-qi-inline/8.1-jian-jie.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
