聊聊gost的ObjectPool


本文摘自网络,作者,侵删。

本文主要研究一下gost的ObjectPool

ObjectPool

gost/bytes/bytes_buffer_pool.go

// Pool is bytes.Buffer Pool
type ObjectPool struct {
    New  New
    pool sync.Pool
}

func NewObjectPool(n New) *ObjectPool {
    return &ObjectPool{New: n}
}

// take returns *bytes.Buffer from Pool
func (p *ObjectPool) Get() PoolObject {
    v := p.pool.Get()
    if v == nil {
        return p.New()
    }

    return v.(PoolObject)
}

// give returns *byes.Buffer to Pool
func (p *ObjectPool) Put(o PoolObject) {
    o.Reset()
    p.pool.Put(o)
}

// Pool object
type PoolObject interface {
    Reset()
}

type New func() PoolObject
ObjectPool定义了New及sync.Pool属性,它提供了Get、Put方法,同时还有NewObjectPool工程方法;New是一个func,返回PoolObject;PoolObject接口定义了Reset方法

defaultPool

gost/bytes/bytes_buffer_pool.go

var (
    defaultPool *ObjectPool
)

func init() {
    defaultPool = NewObjectPool(func() PoolObject {
        return new(bytes.Buffer)
    })
}

// GetBytesBuffer returns bytes.Buffer from pool
func GetBytesBuffer() *bytes.Buffer {
    return defaultPool.Get().(*bytes.Buffer)
}

// PutIoBuffer returns IoBuffer to pool
func PutBytesBuffer(buf *bytes.Buffer) {
    defaultPool.Put(buf)
}
defaultPool创建的ObjectPool,其Reset方法为new(bytes.Buffer),其GetBytesBuffer将defaultPool.Get()转换为*bytes.Buffer类型

实例

gost/bytes/bytes_buffer_pool_test.go

func TestBytesBufferPool(t *testing.T) {
    buf := GetBytesBuffer()
    bytes := []byte{0x00, 0x01, 0x02, 0x03, 0x04}
    buf.Write(bytes)
    if buf.Len() != len(bytes) {
        t.Error("iobuffer len not match write bytes' size")
    }
    PutBytesBuffer(buf)
    //buf2 := GetBytesBuffer()
    // https://go-review.googlesource.com/c/go/+/162919/
    // before go 1.13, sync.Pool just reserves some objs before every gc and will be cleanup by gc.
    // after Go 1.13, maybe there are many reserved objs after gc.
    //if buf != buf2 {
    //    t.Errorf("buf pointer %p != buf2 pointer %p", buf, buf2)
    //}
}
这里展示用GetBytesBuffer获取buf,再通过PutBytesBuffer归还buf

小结

gost的ObjectPool定义了New及sync.Pool属性,它提供了Get、Put方法,同时还有NewObjectPool工程方法;New是一个func,返回PoolObject;PoolObject接口定义了Reset方法。

doc

  • gost

本文来自:Segmentfault

感谢作者:codecraft

查看原文:聊聊gost的ObjectPool

相关阅读 >>

Go设计模式之工厂模式浅谈2

聊聊dubbo-Go-proxy的apifilter

tools easily execute sql against structured text like csv or tsv

模块二 Go语言进阶技术-错误处理(下)

Go-zero 如何扛住流量冲击(一)

手撸Golang 结构型设计模式 代理模式

leetcode Go

Golang可以做些什么?

Go无缓冲通道的陷阱

聊聊dubbo-Go-proxy的client

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...