前言

sync.Pool 是临时对象池,存储的是临时对象,不可以用它来存储 socket 长连接和数据库连接池等。

sync.Pool 本质是用来保存和复用临时对象,以减少内存分配,降低 GC 压力,比如需要使用一个对象,就去 Pool 里面拿,如果拿不到就分配一份,这比起不停生成新的对象,用完了再等待 GC 回收要高效的多。

sync.Pool

sync.Pool 的使用很简单,看下示例代码:

  1. package student
  2. import (
  3. "sync"
  4. )
  5. type student struct {
  6. Name string
  7. Age int
  8. }
  9. var studentPool = &sync.Pool{
  10. New: func() interface{} {
  11. return new(student)
  12. },
  13. }
  14. func New(name string, age int) *student {
  15. stu := studentPool.Get().(*student)
  16. stu.Name = name
  17. stu.Age = age
  18. return stu
  19. }
  20. func Release(stu *student) {
  21. stu.Name = ""
  22. stu.Age = 0
  23. studentPool.Put(stu)
  24. }

当使用 student 对象时,只需要调用 New() 方法获取对象,获取之后使用 defer 函数进行释放即可。

  1. stu := student.New("tom", 30)
  2. defer student.Release(stu)
  3. // 业务逻辑
  4. ...

关于 sync.Pool 里面的对象具体是什么时候真正释放,是由系统决定的。

小结

  1. 一定要注意存储的是临时对象!
  2. 一定要注意 Get 后,要调用 Put

以上,希望对你能够有所帮助。

推荐阅读