Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use time.Timer instead of time.After in either-or cases to avoid memory leak #1623

Closed
arijitAD opened this issue Jun 4, 2021 · 0 comments · Fixed by #1650
Closed

Use time.Timer instead of time.After in either-or cases to avoid memory leak #1623

arijitAD opened this issue Jun 4, 2021 · 0 comments · Fixed by #1650
Assignees

Comments

@arijitAD
Copy link
Contributor

arijitAD commented Jun 4, 2021

Issue summary

The docs for time.After says

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.

We should replace time.After with time.Timer if we want to poll some code to avoid unnecessary allocation and deallocation.

Benchmark to compare time.After vs time.Sleep vs time.Timer vs time.Ticker

BenchmarkSleep-16    	   40676	     32230 ns/op	       0 B/op	       0 allocs/op
BenchmarkAfter-16    	   10000	    114656 ns/op	  200001 B/op	    3000 allocs/op
BenchmarkReset-16    	   27517	     44791 ns/op	     200 B/op	       3 allocs/op
BenchmarkTicker-16    	   31257	     35621 ns/op	     200 B/op	       3 allocs/op

https://play.golang.org/p/jfmFQQQv-0I

Other information and links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants