转自:链接,文章不全。
    在谢大群里看到有同学在讨论time.After泄漏的问题,就算时间到了也不会释放,瞬间就惊呆了,忍不住做了试验,结果发现应该没有这么的恐怖的,是有泄漏的风险不过不算是泄漏,先看API的说明:

    1. // After waits for the duration to elapse and then sends the current time
    2. // on the returned channel.
    3. // It is equivalent to NewTimer(d).C.
    4. // The underlying Timer is not recovered by the garbage collector
    5. // until the timer fires. If efficiency is a concern, use NewTimer
    6. // instead and call Timer.Stop if the timer is no longer needed.
    7. func After(d Duration) <-chan Time {
    8. return NewTimer(d).C
    9. }

    提到了一句The underlying Timer is not recovered by the garbage collector,这句挺吓人不会被GC回收,不过后面还有条件until the timer fires,说明fire后是会被回收的,所谓fire就是到时间了,写个例子证明下压压惊:

    1. package main
    2. import "time"
    3. func main() {
    4. for {
    5. <- time.After(10 * time.Nanosecond)
    6. }
    7. }

    显示内存稳定在5.3MB,CPU为1.61%,肯定被GC回收了的。当然如果放在goroutine也是没有问题的,一样会回收:

    1. package main
    2. import "time"
    3. func main() {
    4. for i := 0; i < 100; i++ {
    5. go func(){
    6. for {
    7. <- time.After(10 * time.Nanosecond)
    8. }
    9. }()
    10. }
    11. time.Sleep(1 * time.Hour)
    12. }

    只是资源消耗会多一点,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是不会立马释放的(到期后才会释放),比如这种:

    1. select {
    2. case time.After(3*time.Second):
    3. return errTimeout
    4. case packet := packetChannel:
    5. // process packet.
    6. }

    如果packet非常多,那么总是会走到下面的分支,上面的timer不会立刻释放而是在3秒后才能释放,和下面代码一样:

    1. package main
    2. import "time"
    3. func main() {
    4. for {
    5. select {
    6. case <-time.After(3 * time.Second):
    7. default:
    8. }
    9. }
    10. }

    这个时候,就相当于会堆积了3秒的timer没有释放而已,会不断的新建和释放timer,内存会稳定在2.8GB,这个当然就不是最好的了,可以主动释放:

    1. package main
    2. import "time"
    3. func main() {
    4. for {
    5. t := time.NewTimer(3*time.Second)
    6. select {
    7. case <- t.C:
    8. default:
    9. t.Stop()
    10. }
    11. }
    12. }

    这样就不会占用2.8GB内存了,只有5MB左右。因此,总结下这个After的说明:

    GC肯定会回收time.After的,就在d之后就回收。一般情况下让系统自己回收就好了。
    如果有效率问题,应该使用Timer在不需要时主动Stop。大部分时候都不用考虑这个问题的。