github.com/blend/go-sdk@v1.20240719.1/bufferutil/pool.go (about) 1 /* 2 3 Copyright (c) 2024 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package bufferutil 9 10 import ( 11 "bytes" 12 "sync" 13 ) 14 15 /* 16 NewPool returns a new Pool, which returns bytes buffers pre-sized to a given minimum size. 17 18 The purpose of a buffer pool is to reduce the number of gc collections incurred when using bytes buffers 19 repeatedly; instead of marking the buffer as to be collected, it is returned to the pool to be re-used. 20 21 Example: 22 23 pool := bufferutil.NewPool(1024) // pre-allocate 1024 bytes per buffer. 24 25 func() { 26 buf := pool.Get() 27 defer pool.Put(buf) 28 29 // do things with the buffer ... 30 }() 31 */ 32 func NewPool(bufferSize int) *Pool { 33 return &Pool{ 34 Pool: sync.Pool{New: func() interface{} { 35 b := bytes.NewBuffer(make([]byte, bufferSize)) 36 b.Reset() 37 return b 38 }}, 39 } 40 } 41 42 // Pool is a sync.Pool of bytes.Buffer. 43 type Pool struct { 44 sync.Pool 45 } 46 47 // Get returns a pooled bytes.Buffer instance. 48 func (p *Pool) Get() *bytes.Buffer { 49 return p.Pool.Get().(*bytes.Buffer) 50 } 51 52 // Put returns the pooled instance. 53 func (p *Pool) Put(b *bytes.Buffer) { 54 b.Reset() 55 p.Pool.Put(b) 56 }