Go

sync.Pool — Reuse Allocations

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`sync.Pool` keeps a pool of reusable objects to reduce allocator pressure in hot paths. Good for byte buffers, JSON encoders, or anything you allocate frequently and only need briefly.
Go
Raw
package main

import (
    "bytes"
    "fmt"
    "sync"
)

var bufPool = sync.Pool{
    New: func() any { return new(bytes.Buffer) },
}

func processRequest(payload []byte) string {
    buf := bufPool.Get().(*bytes.Buffer)
    defer func() {
        buf.Reset()                          // wipe before returning
        bufPool.Put(buf)
    }()

    buf.WriteString("processed: ")
    buf.Write(payload)
    return buf.String()
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            fmt.Println(processRequest([]byte(fmt.Sprintf("req-%d", i))))
        }(i)
    }
    wg.Wait()
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.