dgryski / go-perfbook

Thoughts on Go performance optimization

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use `ctx.Done()` instead of `time.NewTimer()` as a replacement of `time.After()`?

RussellLuo opened this issue · comments

Hi there!

Regarding this suggestion:

time.After() leaks until it fires; use t := NewTimer(); t.Stop() / t.Reset()

AFAIK, I'm afraid time.NewTimer() is also difficult to use correctly.

How about using ctx.Done() as a replacement of time.After()?

For example, instead of doing this:

select {
case value := <-C:
	// handle value
case <-time.After(5 * time.Second):
	// timeout elapses
}

Maybe we should do this:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

select {
case value := <-C:
	// handle value
case <-ctx.Done():
	// timeout elapses
}