go sync.pool 学习笔记

概述 sync.pool 对象池可以用来复用临时对象,减少内存压力,降低 GC 压力。 示例 基本用法 1type Worker struct{} 2 3func (w *Worker) Name() string { 4 return "worker" 5} 6 7func main() { 8 workerPool := sync.Pool{New: func() interface{} { 9 return Worker{} 10 }} 11 12 worker := workerPool.Get().(Worker) 13 defer workerPool.Put(worker) 14 15 name := worker.Name() 16 fmt.Println(name) 17} sync.pool 是单对象池,不是多对象池。基本使用方法是 Get 和 Put 方法,Get 用来从对象池中取对象,Put 用来将不用的对象放回对象池中。 ...

2025-11-09 · xhy