Table of Contents
defer performance optimization by 30%
Comparison between before and now
defer minimum unit: _defer
Back to the problem itself, after knowing the principle of defer optimization. Then "Will the defer keyword in the loop have any performance impact?"
显式循环
隐式循环
总结
Home Backend Development Golang Pay attention to these two points when using Go defer!

Pay attention to these two points when using Go defer!

Jul 10, 2021 pm 03:09 PM
golang

defer is a very interesting keyword feature in Go language. The example is as follows:

package main

import "fmt"

func main() {
    defer fmt.Println("煎鱼了")

    fmt.Println("脑子进")
}
Copy after login

The output result is:

脑子进
煎鱼了
Copy after login

A few days ago, some friends in my reader group discussed the following issue:

Pay attention to these two points when using Go defer!

To put it simply, the question is whether there will be any performance impact if using the defer keyword in the for loop?

Because in the design of the underlying data structure of the Go language, defer is a linked list data structure:

Pay attention to these two points when using Go defer!

Everyone is worried that if the loop is too large, the defer linked list will become huge. Not "excellent" enough. Or are you wondering whether the design of Go defer is similar to the Redis data structure design, and I have optimized it myself, but it actually has no big impact?

In today’s article, we will explore the loop Go defer. Will it cause any problems if the underlying linked list is too long? If so, what are the specific impacts?

Start the journey of attracting fish.

defer performance optimization by 30%

In the early years of Go1.13, we conducted a round of performance optimization on defer, which improved defer performance by 30% in most scenarios:

Pay attention to these two points when using Go defer!

Let’s review the changes in Go1.13 and see where Go defer has been optimized. This is the key point of the problem.

Comparison between before and now

In Go1.12 and before, the assembly code when calling Go defer is as follows:

    0x0070 00112 (main.go:6)    CALL    runtime.deferproc(SB)
    0x0075 00117 (main.go:6)    TESTL    AX, AX
    0x0077 00119 (main.go:6)    JNE    137
    0x0079 00121 (main.go:7)    XCHGL    AX, AX
    0x007a 00122 (main.go:7)    CALL    runtime.deferreturn(SB)
    0x007f 00127 (main.go:7)    MOVQ    56(SP), BP
Copy after login

In Go1.13 and later, the assembly code when calling Go defer The code is as follows:

    0x006e 00110 (main.go:4)    MOVQ    AX, (SP)
    0x0072 00114 (main.go:4)    CALL    runtime.deferprocStack(SB)
    0x0077 00119 (main.go:4)    TESTL    AX, AX
    0x0079 00121 (main.go:4)    JNE    139
    0x007b 00123 (main.go:7)    XCHGL    AX, AX
    0x007c 00124 (main.go:7)    CALL    runtime.deferreturn(SB)
    0x0081 00129 (main.go:7)    MOVQ    112(SP), BP
Copy after login

From the assembly point of view, it seems that the original method of calling runtime.deferproc has been changed to the method of calling runtime.deferprocStack. Is this done? What optimization?

Wehold our doubts and continue reading.

defer minimum unit: _defer

Compared with previous versions, the minimum unit of Go defer_defer structure mainly adds heap Field:

type _defer struct {
    siz     int32
    siz     int32 // includes both arguments and results
    started bool
    heap    bool
    sp      uintptr // sp at time of defer
    pc      uintptr
    fn      *funcval
    ...
Copy after login

This field is used to identify whether this _defer is allocated on the heap or the stack. The other fields have not been clearly changed, so we can focus on # The stack of ##defer is allocated, let’s see what is done.

deferprocStack

func deferprocStack(d *_defer) {
    gp := getg()
    if gp.m.curg != gp {
        throw("defer on system stack")
    }
    
    d.started = false
    d.heap = false
    d.sp = getcallersp()
    d.pc = getcallerpc()

    *(*uintptr)(unsafe.Pointer(&d._panic)) = 0
    *(*uintptr)(unsafe.Pointer(&d.link)) = uintptr(unsafe.Pointer(gp._defer))
    *(*uintptr)(unsafe.Pointer(&gp._defer)) = uintptr(unsafe.Pointer(d))

    return0()
}
Copy after login

This piece of code is quite conventional, mainly to obtain the function stack pointer of the calling

defer function, the specific address of the parameters passed into the function, and the PC (program counter ), this has been introduced in detail in the previous article "In-depth Understanding of Go Defer", so I won't go into details here.

What is so special about this

deferprocStack?

You can see that it sets

d.heap to false, which means that the deferprocStack method is for _defer The application scenario allocated on the stack.

deferproc

The question is, where does it handle the application scenarios allocated on the heap?

func newdefer(siz int32) *_defer {
    ...
    d.heap = true
    d.link = gp._defer
    gp._defer = d
    return d
}
Copy after login
The specific

newdefer is where it is called, as follows:

func deferproc(siz int32, fn *funcval) { // arguments of fn follow fn
    ...
    sp := getcallersp()
    argp := uintptr(unsafe.Pointer(&fn)) + unsafe.Sizeof(fn)
    callerpc := getcallerpc()

    d := newdefer(siz)
    ...
}
Copy after login
It is very clear that the

deferproc method called in the previous version, Now used to correspond to scenarios allocated on the heap.

Summary

    What is certain is that
  • deferproc has not been removed, but the process has been optimized.
  • The Go compiler will choose to use the
  • deferproc or deferprocStack method according to the application scenario. They are respectively for the usage scenario of allocation on the heap and stack.
Where is the optimization?

The main optimization lies in the change of the stack allocation rules of its defer object. The measures are:

The compiler's ## of
defer #for-loop Iterate deeply for analysis. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// src/cmd/compile/internal/gc/esc.go case ODEFER:     if e.loopdepth == 1 { // top level         n.Esc = EscNever // force stack allocation of defer record (see ssa.go)         break     }</pre><div class="contentsignin">Copy after login</div></div>If the Go compiler detects that the loop depth (loopdepth) is 1, it sets the result of escape analysis and will be allocated on the stack, otherwise it will be allocated on the heap.

// src/cmd/compile/internal/gc/ssa.go
case ODEFER:
    d := callDefer
    if n.Esc == EscNever {
        d = callDeferStack
    }
    s.call(n.Left, d)
Copy after login

This eliminates the large amount of performance overhead caused by frequent calls to

systemstack

, mallocgc and other methods in the past, thereby improving performance in most scenarios. Loop call defer

Back to the problem itself, after knowing the principle of defer optimization. Then "Will the defer keyword in the loop have any performance impact?"

The most direct impact is that about 30% of the performance optimization is completely lost, and due to incorrect posture, theoretically defer has The overhead (the linked list becomes longer) also becomes larger and the performance becomes worse.

So we need to avoid the following two scenarios:

  • 显式循环:在调用 defer 关键字的外层有显式的循环调用,例如:for-loop 语句等。
  • 隐式循环:在调用 defer 关键字有类似循环嵌套的逻辑,例如:goto 语句等。

显式循环

第一个例子是直接在代码的 for 循环中使用 defer 关键字:

func main() {
    for i := 0; i <p>这个也是最常见的模式,无论是写爬虫时,又或是 Goroutine 调用时,不少人都喜欢这么写。</p><p>这属于显式的调用了循环。</p><h3 id="隐式循环">隐式循环</h3><p>第二个例子是在代码中使用类似 <code>goto</code> 关键字:</p><pre class="brush:php;toolbar:false">func main() {
    i := 1
food:
    defer func() {}()
    if i == 1 {
        i -= 1
        goto food
    }
}
Copy after login

这种写法比较少见,因为 goto 关键字有时候甚至会被列为代码规范不给使用,主要是会造成一些滥用,所以大多数就选择其实方式实现逻辑。

这属于隐式的调用,造成了类循环的作用。

总结

显然,Defer 在设计上并没有说做的特别的奇妙。他主要是根据实际的一些应用场景进行了优化,达到了较好的性能。

虽然本身 defer 会带一点点开销,但并没有想象中那么的不堪使用。除非你 defer 所在的代码是需要频繁执行的代码,才需要考虑去做优化。

否则没有必要过度纠结,在实际上,猜测或遇到性能问题时,看看 PProf 的分析,看看 defer 是不是在相应的 hot path 之中,再进行合理优化就好。

所谓的优化,可能也只是去掉 defer 而采用手动执行,并不复杂。在编码时避免踩到 defer 的显式和隐式循环这 2 个雷区就可以达到性能最大化了。

更多golang相关技术文章,请访问golang教程栏目!

The above is the detailed content of Pay attention to these two points when using Go defer!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

Comparison of advantages and disadvantages of golang framework Comparison of advantages and disadvantages of golang framework Jun 05, 2024 pm 09:32 PM

The Go framework stands out due to its high performance and concurrency advantages, but it also has some disadvantages, such as being relatively new, having a small developer ecosystem, and lacking some features. Additionally, rapid changes and learning curves can vary from framework to framework. The Gin framework is a popular choice for building RESTful APIs due to its efficient routing, built-in JSON support, and powerful error handling.

What are the best practices for error handling in Golang framework? What are the best practices for error handling in Golang framework? Jun 05, 2024 pm 10:39 PM

Best practices: Create custom errors using well-defined error types (errors package) Provide more details Log errors appropriately Propagate errors correctly and avoid hiding or suppressing Wrap errors as needed to add context

What are the common dependency management issues in the Golang framework? What are the common dependency management issues in the Golang framework? Jun 05, 2024 pm 07:27 PM

Common problems and solutions in Go framework dependency management: Dependency conflicts: Use dependency management tools, specify the accepted version range, and check for dependency conflicts. Vendor lock-in: Resolved by code duplication, GoModulesV2 file locking, or regular cleaning of the vendor directory. Security vulnerabilities: Use security auditing tools, choose reputable providers, monitor security bulletins and keep dependencies updated.

Detailed practical explanation of golang framework development: Questions and Answers Detailed practical explanation of golang framework development: Questions and Answers Jun 06, 2024 am 10:57 AM

In Go framework development, common challenges and their solutions are: Error handling: Use the errors package for management, and use middleware to centrally handle errors. Authentication and authorization: Integrate third-party libraries and create custom middleware to check credentials. Concurrency processing: Use goroutines, mutexes, and channels to control resource access. Unit testing: Use gotest packages, mocks, and stubs for isolation, and code coverage tools to ensure sufficiency. Deployment and monitoring: Use Docker containers to package deployments, set up data backups, and track performance and errors with logging and monitoring tools.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

See all articles