Golang简单的对象池

来源:互联网 发布:fastdfs nginx 404 编辑:程序博客网 时间:2024/06/05 16:39

Golang简单的对象池

  • 复用的好处
    • 减少gc压力
    • 减少不必要的内存分配
import (    "fmt"    "sync")var bufPool sync.Pooltype buf struct {    b []byte}func main() {    for {        var bf *buf        // 从池中取数据        v := bufPool.Get()        if v == nil {            //若不存在buf,创建新的            fmt.Println("no buf ,create!")            bf = &buf{                b: make([]byte, 10),            }        } else {            // 池里存在buf,v这里是interface{},需要做类型转换            bf = v.(*buf)        }        fmt.Println("使用数据", bf)        // bf使命完成,放入池中        bufPool.Put(bf)    }}
1 0
原创粉丝点击