go / expert
Snippet
GC-Optimized Object Reuse with Typed Buffer Pooling via sync.Pool
sync.Pool manages reusable temporary objects to dramatically decrease Garbage Collector (GC) pressure in allocation-heavy environments. High-performance design patterns combine sync.Pool with capacity bounds on returning objects to prevent retainment of bloated dynamically grown slices.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package mainimport ("bytes""fmt""sync")type BufferPool struct {pool sync.Pool}func NewBufferPool(capacity int) *BufferPool {return &BufferPool{pool: sync.Pool{New: func() any {return bytes.NewBuffer(make([]byte, 0, capacity))},},}}func (p *BufferPool) Get() *bytes.Buffer {buf := p.pool.Get().(*bytes.Buffer)buf.Reset()return buf}func (p *BufferPool) Put(buf *bytes.Buffer) {// Prevent pooling bloated buffers to keep memory footprint boundif buf.Cap() > 64*1024 {return}p.pool.Put(buf)}func main() {bp := NewBufferPool(4096)buf := bp.Get()buf.WriteString("High-throughput stream processing")fmt.Println(buf.String())bp.Put(buf)}
Breakdown
1
New: func() any { return bytes.NewBuffer(make([]byte, 0, capacity)) }
Defines the allocator fallback constructor invoked when the pool has no available cached instance.
2
if buf.Cap() > 64*1024 { return }
Enforces a strict upper bound check to prevent oversized buffers from remaining pooled permanently and exhausting system memory.