Sync Pool Byte Buffer Reuse

Recycle byte buffers with sync.Pool to cut allocation churn in hot paths, using Get/Put discipline and clearing on store.

GoResilience

Code

gosnippet
45 lines
package main

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

var bufferPool = sync.Pool{
	New: func() interface{} {
		return new(bytes.Buffer) // 池空时的兜底构造
	},
}

func renderJSON(name string, score int) string {
	buf := bufferPool.Get().(*bytes.Buffer)
	defer func() {
		buf.Reset()         // 必须清零,防止跨使用者数据泄漏
		bufferPool.Put(buf) // 归还前重置容量状态
	}()

	buf.WriteString("{\"name\":\"")
	buf.WriteString(name)
	buf.WriteString("\",\"score\":")
	fmt.Fprintf(buf, "%d}", score)
	return buf.String()
}

func main() {
	results := make([]string, 0, 8)
	var wg sync.WaitGroup

	for i := 0; i < 8; i++ {
		wg.Add(1)
		go func(n int) {
			defer wg.Done()
			results = append(results[:n:n], renderJSON(fmt.Sprintf("user-%d", n), n*10))
		}(i)
	}
	wg.Wait()

	for _, r := range results {
		fmt.Println(r)
	}
}

How it works

Sync Pool Byte Buffer Reuse comes down to the functions renderJSON and main.

Iteration happens inside for i := 0; i < 8; i++ — everything outside it runs once. The task is handed to a goroutine and runs concurrently. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Putting it to use

The primary signature is func renderJSON(name string, score int) string

There are 1 call inside main — renderJSON — executed top to bottom.

Core lines

results = append(results[:n:n], renderJSON(fmt.Sprintf("user-%d", n), n*10))
var bufferPool = sync.Pool{
	New: func() interface{} {
		return new(bytes.Buffer) // 池空时的兜底构造
	},
}
for _, r := range results {
	fmt.Println(r)
}

Interactive Tools for This Topic

FAQ

How do you run Sync Pool Byte Buffer Reuse?
Direct execution is enough; the script has no external requirements.