golang有用的库及工具 之 sync.Pool改造
来源:互联网 发布:linux 复制重命名 编辑:程序博客网 时间:2024/05/05 14:45
一个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 collectionimport ( "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的负担,从而减少内存开销。
阅读全文
0 0
- golang有用的库及工具 之 sync.Pool改造
- golang的临时对象池sync.Pool
- golang有用的库及工具 之 一致性哈希(Consistent Hashing)算法
- golang有用的库及工具 之 zap.Logger包 使用
- golang有用的库及工具 之 缓存淘汰算法--LRU算法
- golang有用的库及工具 之 字符串转换 获取32位 uint32位hash 方法 MurmurHash哈希
- golang有用的库及工具 之 fasthttp客户端 最通用最有效最简单使用方式
- golang包学习之sync
- golang同步之sync包
- golang waitgroup 及 sync.Once 示例
- go的临时对象池--sync.Pool
- 说清楚了sync.pool的文章
- golang工具的坑
- golang sync WaitGroup
- golang sync mutex 互斥锁
- golang sync WaitGroup
- GOLANG sync.WaitGroup讲解
- GOLANG sync.Once
- 什么是硬分叉,什么是软分叉,什么是共识?
- Spring详解
- 学习蓝桥杯过程中总结day1
- return()、exit()、_exit()、aboart()函数区别
- Android视频加水印和压缩
- golang有用的库及工具 之 sync.Pool改造
- IDEA常用快捷键
- Linkit ONE开发板实验00-开发板简介
- Mybatis入门到精通-搭建MyBatis技术环境
- 使用symbolicatecrash分析crash文件
- 关于测试的一些小要点
- 存储过程失效
- linux文件系统详解
- hiho 1611 气泡图 [Offer收割]编程练习赛32 Problem A 数学公式暴力