一个sync.Pool对象就是一组临时对象的集合。Pool是协程安全的。
Pool用于存储那些被分配了但是没有被使用,而未来可能会使用的值,以减小垃圾回收的压力。
如下是使用的两种方式:
一:
func main() { for index := 0; index < 100; index++ { go sss() //go ssse() } time.Sleep(2 * time.Second) } var sp = &sync.Pool{} func sss() { sin := sp.Get() var buf *bytes.Buffer if sin != nil { buf = sin.(*bytes.Buffer) } else { buf = bytes.NewBuffer(make([]byte, 0, 65536)) } buf.Write([]byte("hello world")) fmt.Println(buf.String()) buf.Reset() sp.Put(buf) }
二:
package collection import ( "bytes" "sync" ) type BufferPool struct { sync.Pool } func NewBufferPool(bufferSize int) (bp *BufferPool) { return &BufferPool{ sync.Pool{ New: func() interface{} { return bytes.NewBuffer(make([]byte, 0, bufferSize)) }, }, } } func (bp *BufferPool) Get() *bytes.Buffer { return bp.Pool.Get().(*bytes.Buffer) } func (bp *BufferPool) Put(b *bytes.Buffer) { b.Reset() bp.Pool.Put(b) }
var buffers = collection.NewBufferPool(65536) func main() { for index := 0; index < 100; index++ { go sss() //go ssse() } time.Sleep(2 * time.Second) } func ssse() { buf := buffers.Get() buf.Write([]byte("hello world")) fmt.Println(buf.String()) buffers.Put(buf) }
第二种采用了实现其 sync.Pool 的 new 接口,使用起来更加的方便快捷。
总结:sync.Pool的定位不是做类似连接池的东西,它的用途仅仅是增加对象重用的几率,减少gc的负担,从而减少内存开销。
来源:CSDN
作者:逆月林
链接:https://blog.csdn.net/niyuelin1990/article/details/78310002