github.com/duomi520/utils@v0.0.0-20240430123446-e03a4cddd6ec/pool.go (about) 1 package utils 2 3 import ( 4 "sync" 5 "sync/atomic" 6 ) 7 8 var defaultPool sync.Pool 9 var defaultByteSize = uint64(1024) 10 11 func init() { 12 defaultPool.New = func() interface{} { 13 return &[]byte{} 14 } 15 } 16 17 func AllocSlice() *[]byte { 18 v := defaultPool.Get() 19 if v != nil { 20 return v.(*[]byte) 21 } 22 b := make([]byte, 0, atomic.LoadUint64(&defaultByteSize)) 23 return &b 24 } 25 func FreeSlice(x *[]byte) { 26 defaultPool.Put(x) 27 } 28 29 func ChangeDefaultByteSize(n uint64) { 30 atomic.StoreUint64(&defaultByteSize, n) 31 } 32 33 // https://github.com/valyala/bytebufferpool