Preface
sync.Pool
is a temporary object pool, which stores temporary objects. You cannot use it to store socket
long connections and database connection pools.
sync.Pool
is essentially used to save and reuse temporary objects to reduce memory allocation and reduce GC pressure. For example, if you need to use an object, go to the pool to get it, and if you can’t get it, allocate a copy. This is compared to constantly generating new ones. It is much more efficient to wait for the GC to reclaim the object when it is used up.
sync.Pool
sync.Pool
is very simple, look at the sample code:
package student
import (
"sync"
)
type student struct {
Name string
Age int
}
var studentPool = &sync.Pool{
New: func() interface{} {
return new(student)
},
}
func New(name string, age int) *student {
stu := studentPool.Get().(*student)
stu.Name = name
stu.Age = age
return stu
}
func Release(stu *student) {
stu.Name = ""
stu.Age = 0
studentPool.Put(stu)
}
When using the student
object, you only need to call the New()
method to get the object, and then use the defer
function to release it.
stu := student.New("tom", 30)
defer student.Release(stu)
// 业务逻辑
...
The actual release of the objects in sync.Pool
summary
- Be sure to store temporary objects!
- We must pay attention to
Get
later, to callPut
!
The above, I hope it can help you.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。