go sync.Pool 包简单总结

// 自带pool 的用途总结 
// 1. sync 中自带的 包没有控制 pool中对象的数量, 当你pool中存在你put之后的对象的时候,会复用你创建的。如果不存在,则会通过new去创建并且返回
// 2. sync 中服用的大体都是结构体,缓存, 对于长链接。 他会不告知清理 所以又可能会重建
package main import (
"fmt" "sync" ) func main() { bPool := sync.Pool{ New: func() interface{} { return make([]int, 5) }, } get := bPool.Get().([]int) get[0] = 1 bPool.Put(get) // pool 中存在刚刚更改的对象直接获取服用 get0 := bPool.Get() fmt.Println("get0: ", get0) bPool.Put([]int{1,23,4,6,6}) // pool 中存在刚刚put的对象不需要创建 get1 := bPool.Get() fmt.Println("get1: ", get1) // pool 中不存在对象 需要new get2 := bPool.Get() fmt.Println("get2: ", get2) get3 := bPool.Get() fmt.Println("get3: ", get3) } ====> get0: [1 0 0 0 0] get1: [1 23 4 6 6] get2: [0 0 0 0 0] get3: [0 0 0 0 0]

 

posted @ 2021-12-29 16:24  Black_Climber  阅读(154)  评论(0编辑  收藏  举报