Essential Go edit forum

sync.Pool for better performance

Allocating and freeing objects with high frequency can be relatively expensive.

A common technique for improving performance is re-using memory.

sync.Pool is a thread-safe cache for re-using allocations.

package main

import (

var pool = sync.Pool{
    // New creates an object when the pool has nothing available to return.
    // New must return an interface{} to make it flexible. You have to cast
    // your type after getting it.
    New: func() interface{} {
        // Pools often contain things like *bytes.Buffer, which are
        // temporary and re-usable.
        return &bytes.Buffer{}

func main() {
    // When getting from a Pool, you need to cast
    s := pool.Get().(*bytes.Buffer)
    // We write to the object
    // Then put it back

    // Pools can return dirty results

    // Get 'another' buffer
    s = pool.Get().(*bytes.Buffer)
    // Write to it
    // At this point, if GC ran, this buffer *might* exist already, in
    // which case it will contain the bytes of the string "dirtyappend"
    // So use pools wisely, and clean up after yourself

    // When you clean up, your buffer should be empty
    s = pool.Get().(*bytes.Buffer)
    // Defer your Puts to make sure you don't leak!
    defer pool.Put(s)
    // This prints "reset!", and not "dirtyappendreset!"

As with all performance optimization techniques you should not over-use sync.Pool.

  ↑ ↓ to navigate     ↵ to select     Esc to close