使用场景
一句话总结:保存和复用临时对象,减少内存分配,降低GC压力
sync.Pool是可伸缩的,也是并发安全的,其大小仅受限于内存大小。sync.Pool用于存储那些被分配了但是没有使用,而未来可能会使用的值。这样就可以不用再次经过内存分配,可直接复用已有对象,减轻GC的压力,从而提升系统性能。
使用方法
声明对象池
type Student struct {
Name string
Age int32
Remark [1024]byte
}
func main() {
var studentPool = sync.Pool{
New: func() interface{
} {
return new(Student)
},
}
}
Get & Put
type Student struct {
Name string
Age int32
Remark [1024]

本文介绍了Go语言中的sync.Pool使用场景和方法,通过示例展示了如何利用sync.Pool减少内存分配和GC压力,以提升系统性能。在性能测试中,尽管对总运行时间影响不大,但sync.Pool显著降低了内存占用,减少了内存分配次数。
最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



