0 day streak
go / intermediate
Snippet

Reusing allocated memory buffers with sync.Pool

Using sync.Pool allows recycling temporary objects, which significantly reduces the workload on the Garbage Collector (GC) during high-throughput operations. The Pool stores temporarily unused buffers and returns them when requested.

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
package main
import (
"bytes"
"fmt"
"sync"
)
var bufPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
func process(val string) {
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
buf.WriteString("Processed: ")
buf.WriteString(val)
fmt.Println(buf.String())
}
func main() {
process("hello")
process("world")
}
Breakdown
1
var bufPool = sync.Pool{
Declares a global sync.Pool and defines a builder function for when the pool is empty.
2
buf := bufPool.Get().(*bytes.Buffer)
Retrieves an available buffer from the pool and type-asserts it back to a bytes.Buffer pointer.
3
bufPool.Put(buf)
Resets the buffer contents and returns the buffer back to the pool for reuse.