转自:链接,文章不全。
在谢大群里看到有同学在讨论time.After泄漏的问题,就算时间到了也不会释放,瞬间就惊呆了,忍不住做了试验,结果发现应该没有这么的恐怖的,是有泄漏的风险不过不算是泄漏,先看API的说明:
// After waits for the duration to elapse and then sends the current time// on the returned channel.// It is equivalent to NewTimer(d).C.// The underlying Timer is not recovered by the garbage collector// until the timer fires. If efficiency is a concern, use NewTimer// instead and call Timer.Stop if the timer is no longer needed.func After(d Duration) <-chan Time {return NewTimer(d).C}
提到了一句The underlying Timer is not recovered by the garbage collector,这句挺吓人不会被GC回收,不过后面还有条件until the timer fires,说明fire后是会被回收的,所谓fire就是到时间了,写个例子证明下压压惊:
package mainimport "time"func main() {for {<- time.After(10 * time.Nanosecond)}}
显示内存稳定在5.3MB,CPU为1.61%,肯定被GC回收了的。当然如果放在goroutine也是没有问题的,一样会回收:
package mainimport "time"func main() {for i := 0; i < 100; i++ {go func(){for {<- time.After(10 * time.Nanosecond)}}()}time.Sleep(1 * time.Hour)}
只是资源消耗会多一点,CPU为4.22%,内存占用6.4MB。因此:
Remark: time.After(d)在d时间之后就会fire,然后被GC回收,不会造成资源泄漏的。
那么API所说的If efficieny is a concern, user NewTimer instead and call Timer.Stop是什么意思呢?这是因为一般time.After会在select中使用,如果另外的分支跑得更快,那么timer是不会立马释放的(到期后才会释放),比如这种:
select {case time.After(3*time.Second):return errTimeoutcase packet := packetChannel:// process packet.}
如果packet非常多,那么总是会走到下面的分支,上面的timer不会立刻释放而是在3秒后才能释放,和下面代码一样:
package mainimport "time"func main() {for {select {case <-time.After(3 * time.Second):default:}}}
这个时候,就相当于会堆积了3秒的timer没有释放而已,会不断的新建和释放timer,内存会稳定在2.8GB,这个当然就不是最好的了,可以主动释放:
package mainimport "time"func main() {for {t := time.NewTimer(3*time.Second)select {case <- t.C:default:t.Stop()}}}
这样就不会占用2.8GB内存了,只有5MB左右。因此,总结下这个After的说明:
GC肯定会回收time.After的,就在d之后就回收。一般情况下让系统自己回收就好了。
如果有效率问题,应该使用Timer在不需要时主动Stop。大部分时候都不用考虑这个问题的。
