search
HomeBackend DevelopmentGolangAn article explains in detail the implementation principle of golang defer

This article is introduced by the go language tutorial column to introduce the implementation principle of golang defer. I hope it will be helpful to friends in need!

defer is a keyword provided by golang, which is called after the function or method completes execution and returns.
Each defer will push the defer function into the stack. When the function or method is called, it will be taken out from the stack for execution. Therefore, the execution order of multiple defers is first in, last out.

for i := 0; i <p><strong>defer trigger timing</strong></p><p>The official website makes it very clear:<br>A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.</p><ol>
<li>When the function wrapped in the defer statement returns</li>
<li>When the function wrapped in the defer statement is executed to the end</li>
<li>
<p>When the current goroutine panics</p>
<pre class="brush:php;toolbar:false">    //输出结果:return前执行defer
   func f1() {
       defer fmt.Println("return前执行defer")
       return 
   }

   //输出结果:函数执行
   // 函数执行到最后
   func f2() {
       defer fmt.Println("函数执行到最后")
       fmt.Println("函数执行")
   }

   //输出结果:panic前  第一个defer在Panic发生时执行,第二个defer在Panic之后声明,不能执行到
   func f3() {
       defer fmt.Println("panic前")
       panic("panic中")
       defer fmt.Println("panic后")
   }

defer, return, return value execution order

Let’s look at 3 examples first

func f1() int { //匿名返回值
        var r int = 6
        defer func() {
                r *= 7
        }()
        return r
}

func f2() (r int) { //有名返回值
        defer func() {
                r *= 7
        }()
        return 6
}

func f3() (r int) { //有名返回值
    defer func(r int) {
        r *= 7
    }(r)
    return 6
}

The execution result of f1 is 6, the execution result of f2 is 42, the execution result of f3 is 6
In the official document of golang It introduces the execution order of return, defer, and return value:
if the surrounding function returns through an explicit return statement, deferred functions are executed after any result parameters are set by that return statement but before the function returns to its caller .

1. Assign the return value first
2. Execute the defer statement
3. Wrap the function return to return

The result of f1 is 6. f1 is an anonymous return value. The anonymous return value is declared when return is executed. Therefore, when defer is declared, the anonymous return value cannot be accessed. Modification of defer will not affect the return value.
f2 first assigns the return value r, r=6, executes the defer statement, defer modifies r, r = 42, and then the function returns.
f3 is a named return value, but because r is used as a parameter of defer, when declaring defer, the parameters are copied and passed, so defer will only affect the local parameters of the defer function and will not affect the calling function. The return value.

Closures and anonymous functions
Anonymous function: A function without a function name.
Closure: A function that can use variables in the scope of another function.

for i := 0; i <p><strong>defer source code analysis</strong><br>The implementation source code of defer is in runtime.deferproc<br>Then run the function runtime.deferreturn before the function returns. <br>First understand the defer structure: </p><pre class="brush:php;toolbar:false">    type _defer struct {
            siz     int32 
            started bool
            sp      uintptr // sp at time of defer
            pc      uintptr
            fn      *funcval
            _panic  *_panic // panic that is running defer
            link    *_defer
    }

sp and pc point to the stack pointer and the caller's program counter respectively, fn is the function passed into the defer keyword, and Panic is the Panic that causes defer to be run. .
Every time a defer keyword is encountered, the defer function will be converted into runtime.deferproc
deferproc creates a delay function through newdefer, and hangs this new delay function on the current goroutine's _defer linked list

    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)
            if d._panic != nil {
                    throw("deferproc: d.panic != nil after newdefer")
            }
            d.fn = fn
            d.pc = callerpc
            d.sp = sp
            switch siz {
            case 0:
                    // Do nothing.
            case sys.PtrSize:
                    *(*uintptr)(deferArgs(d)) = *(*uintptr)(unsafe.Pointer(argp))
            default:
                    memmove(deferArgs(d), unsafe.Pointer(argp), uintptr(siz))
            }
            return0()
    }

newdefer will first take out a _defer structure from the deferpool of sched and current p. If the deferpool does not have _defer, a new _defer will be initialized.
_defer is associated with the current g, so defer is only valid for the current g.
d.link = gp._defer
gp._defer = d //Use a linked list to connect all defers of the current g

    func newdefer(siz int32) *_defer {
            var d *_defer
            sc := deferclass(uintptr(siz))
            gp := getg()
            if sc  0 {
                            d = pp.deferpool[sc][n-1]
                            pp.deferpool[sc][n-1] = nil
                            pp.deferpool[sc] = pp.deferpool[sc][:n-1]
                    }
            }
            ......
            d.siz = siz
            d.link = gp._defer
            gp._defer = d
            return d
    }

deferreturn Take out the _defer linked list from the current g and execute it, each _defer call freedefer releases the _defer structure and puts the _defer structure into the deferpool of the current p.

defer performance analysis
defer is very useful in development for releasing resources, capturing Panic, etc. It is possible that some developers have not considered the impact of defer on program performance and abuse defer in their programs.
It can be found in the performance test that defer still has some impact on performance. Yuchen's Go performance optimization tips 4/1, there are some tests on the extra overhead caused by defer statements.

Test code

    var mu sync.Mutex
    func noDeferLock() {
        mu.Lock()
        mu.Unlock()
    }   

    func deferLock() {
        mu.Lock()
        defer mu.Unlock()
    }          
    
    func BenchmarkNoDefer(b *testing.B) {
        for i := 0; i <p><strong>Test result:</strong></p><pre class="brush:php;toolbar:false">    BenchmarkNoDefer-4      100000000               11.1 ns/op
    BenchmarkDefer-4        36367237                33.1 ns/op

It can be known from the previous source code analysis that defer will first call deferproc , these will copy parameters, and deferreturn will also extract relevant information and delay execution. These are more expensive than directly calling a statement.

The performance of defer is not high. Each defer takes 20ns. If it occurs multiple times in a func, the performance consumption is 20ns*n. The cumulative waste of CPU resources is very large.

Solution: Except when exception capture is required, defer must be used; for other resource recycling defers, you can use goto to jump to the resource recycling code area after judging failure. For competitive resources, you can release the resources immediately after use, so that the competitive resources can be optimally used.

For more golang related knowledge, please visit the golangtutorial column!

The above is the detailed content of An article explains in detail the implementation principle of golang defer. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

聊聊Golang中的几种常用基本数据类型聊聊Golang中的几种常用基本数据类型Jun 30, 2022 am 11:34 AM

本篇文章带大家了解一下golang 的几种常用的基本数据类型,如整型,浮点型,字符,字符串,布尔型等,并介绍了一些常用的类型转换操作。

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

聊聊Golang自带的HttpClient超时机制聊聊Golang自带的HttpClient超时机制Nov 18, 2022 pm 08:25 PM

​在写 Go 的过程中经常对比这两种语言的特性,踩了不少坑,也发现了不少有意思的地方,下面本篇就来聊聊 Go 自带的 HttpClient 的超时机制,希望对大家有所帮助。

go语言是否需要编译go语言是否需要编译Dec 01, 2022 pm 07:06 PM

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

golang map怎么删除元素golang map怎么删除元素Dec 08, 2022 pm 06:26 PM

删除map元素的两种方法:1、使用delete()函数从map中删除指定键值对,语法“delete(map, 键名)”;2、重新创建一个新的map对象,可以清空map中的所有元素,语法“var mapname map[keytype]valuetype”。

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft