Reuse Buffers with sync.Pool
Cut per-request allocations by borrowing bytes.Buffer from sync.Pool, copying the encoded JSON, and always returning the buffer.
Code
package main
import (
"bytes"
"encoding/json"
"fmt"
"sync"
)
var bufferPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
func EncodeJSON(value any) ([]byte, error) {
buffer := bufferPool.Get().(*bytes.Buffer)
buffer.Reset()
defer bufferPool.Put(buffer)
if err := json.NewEncoder(buffer).Encode(value); err != nil {
return nil, err
}
out := make([]byte, buffer.Len())
copy(out, buffer.Bytes())
return out, nil
}
func main() {
type payload struct {
ID int `json:"id"`
Name string `json:"name"`
}
encoded, err := EncodeJSON(payload{ID: 1, Name: "Ada"})
if err != nil {
panic(err)
}
fmt.Print(string(encoded))
fmt.Println(bytes.Equal(encoded, []byte("{\"id\":1,\"name\":\"Ada\"}\n")))
}
What the code does
Reuse Buffers with sync.Pool is built around the functions EncodeJSON and main.
Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
What to watch for
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
Entry signature: func EncodeJSON(value any) ([]byte, error)
Launch the file; main takes over and steps through EncodeJSON.
Statements that matter
func EncodeJSON(value any) ([]byte, error) {
buffer := bufferPool.Get().(*bytes.Buffer)
buffer.Reset()
defer bufferPool.Put(buffer)
if err := json.NewEncoder(buffer).Encode(value); err != nil {
return nil, err
}
out := make([]byte, buffer.Len())
copy(out, buffer.Bytes())
return out, nil
}
var bufferPool = sync.Pool{
New: func() any { return new(bytes.Buffer) },
}
if err != nil {
panic(err)
}
Interactive Tools for This Topic
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does the snippet panic on failure?
- Through `error` values — the snippet checks `err != nil` at 2 sites, and the entry flow turns failures into `panic(err)`.
- How do you run Reuse Buffers with sync.Pool?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.