Timer, Ticker的区别引出变量的逃逸情况.引发的思考

Timer

Timer 定义后固定只执行一次,使用Reset会再触发一次.
timer := time.NewTimer(time.Second)   //Timer 定义后固定只执行一次,使用Reset会再触发一次.
//Timer的实现
    go func(t *time.Timer) {
        for {
            select {
            case <-t.C:
                fmt.Println("timer:", 22)
                t.Reset(time.Second)
            }

        }
    }(timer)

Ticker

Ticker一但被定义, 每隔一段时间会自动触发
ticker := time.NewTicker(time.Second) //Ticker一但被定义, 每隔一段时间会自动触发.

//Ticker的实现
    go func(t *time.Ticker) {
        for {
            select {
            case <-t.C:
                fmt.Printf("ticker:%v\n", 11)
            }
        }
    }(ticker) //

以上go func(){}另一种写, 不使用形参.

go tool compile -m timer.go

以下是编译的过程, 看不太懂. 只知道变量逃逸了. 望高手指教.
timer.go:41:15: inlining call to fmt.Printf
timer.go:51:16: inlining call to fmt.Println
timer.go:61:9: inlining call to time.(*Ticker).Stop
timer.go:62:10: inlining call to time.(*Timer).Stop
timer.go:63:14: inlining call to fmt.Println
timer.go:69:13: inlining call to time.(*Timer).Stop
timer.go:70:14: inlining call to time.(*Ticker).Stop
timer.go:25:13: inlining call to fmt.Println
timer.go:37:5: func literal escapes to heap
timer.go:37:5: func literal escapes to heap
timer.go:47:5: func literal escapes to heap
timer.go:47:5: func literal escapes to heap
timer.go:59:5: func literal escapes to heap
timer.go:59:5: func literal escapes to heap
timer.go:32:11: leaking param: stop
timer.go:67:5: func literal escapes to heap
timer.go:67:5: func literal escapes to heap
timer.go:41:15: io.Writer(os.Stdout) escapes to heap
timer.go:41:31: 11 escapes to heap
timer.go:51:16: io.Writer(os.Stdout) escapes to heap
timer.go:51:17: "timer:" escapes to heap
timer.go:51:27: 22 escapes to heap
timer.go:47:10: leaking param: t
timer.go:61:9: &time.t.r escapes to heap
timer.go:59:10: leaking param: t
timer.go:62:10: &time.t.r escapes to heap
timer.go:59:26: leaking param: t1
timer.go:63:14: io.Writer(os.Stdout) escapes to heap
timer.go:63:15: "回收资源" escapes to heap
timer.go:69:13: &time.t.r escapes to heap
timer.go:69:3: leaking closure reference timer
timer.go:70:14: &time.t.r escapes to heap
timer.go:70:3: leaking closure reference ticker
timer.go:37:10: Show.func1 t does not escape
timer.go:41:15: Show.func1 []interface {} literal does not escape
timer.go:51:16: Show.func2 []interface {} literal does not escape
timer.go:63:14: Show.func3 []interface {} literal does not escape
timer.go:13:14: make(chan struct {}) escapes to heap
timer.go:18:14: make(chan os.Signal) escapes to heap
timer.go:25:13: io.Writer(os.Stdout) escapes to heap
timer.go:25:14: "END" escapes to heap
timer.go:20:15: main syscall.SIGKILL does not escape
timer.go:20:15: main ... argument does not escape
timer.go:25:13: main []interface {} literal does not escape
:1: os.(*File).close .this does not escape

扩展学习

关于堆栈和指针上的语言力学 https://www.ardanlabs.com/blo...

你可能感兴趣的:(golang)