capypad
0 day streak
go / expert
Snippet

Reducing GC Pressure with sync.Pool

sync.Pool allows for object reuse, significantly reducing the frequency of garbage collection cycles in high-throughput applications by recycling allocated memory.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
var bufferPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
 
func Process(data []byte) {
buf := bufferPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufferPool.Put(buf)
}()
buf.Write(data)
}
Breakdown
1
New: func() any { return new(bytes.Buffer) }
Defines how to create a new object if the pool is empty.
2
bufferPool.Put(buf)
Returns the buffer to the pool after clearing its state for future reuse.