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

snippet
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)
	}
}