Skip to content

Go Sync.Pool: Objects Not Reused

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Go Sync.Pool: Objects Not Reused. We cover key concepts, practical examples, and best practices.

Sync.Pool usage -- Use sync.Pool to temporarily reuse allocated objects and reduce GC pressure.

The Problem

sync.Pool stores temporarily idle objects. Objects may be removed at any time (especially during GC). Pool is NOT a cache. It's for amortizing allocation overhead.

Wrong

var pool = &sync.Pool{
    New: func() interface{} {
        return make([]byte, 1024)
    },
}
buf := pool.Get().([]byte)
// Use buf
pool.Put(buf) // Return to pool

Output:

// Buffer reused, less allocation overhead
func writeResponse(w http.ResponseWriter) {
    buf := bufPool.Get().([]byte)
    defer bufPool.Put(buf)
    buf = buf[:0] // Reset
    buf = append(buf, "data "...)
    w.Write(buf)
}

Output:

// Memory reused across requests. Less GC pressure.

Prevention

  • Pool for temporary objects, not long-term caching
  • Objects may be garbage collected silently
  • Reset objects before reuse (zero length, clear fields)
  • New function creates new object when pool empty
  • Pool reduces allocation count and GC time

Common Mistakes with sync pool

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**When should I use Pool?**

For frequently allocated, short-lived objects like buffers.

When should I NOT use Pool?

For long-lived objects, connections, or objects with cleanup.

Is Pool thread-safe?

Yes. Concurrent Get and Put are safe.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro