性能测试之sync.Pool

Golang sync.Pool

  • 测试平台: M1 Macbook Pro
  • golang版本: 1.18.3

测试代码

package sync_pool

import (
	"bytes"
	"sync"
	"testing"
)

var bufferPool = sync.Pool{
	New: func() interface{} {
		return &bytes.Buffer{}
	},
}

var data = make([]byte, 10000)

func bufferWithPool() {
	buf := bufferPool.Get().(*bytes.Buffer)
	defer func() {
		buf.Reset()
		bufferPool.Put(buf)
	}()
	buf.Write(data)
}

func bufferWithoutPool() {
	var buf bytes.Buffer
	buf.Write(data)
}

func BenchmarkBufferWithPool(b *testing.B) {
	for n := 0; n < b.N; n++ {
		bufferWithPool()
	}
}

func BenchmarkBufferWithoutPool(b *testing.B) {
	for n := 0; n < b.N; n++ {
		bufferWithoutPool()
	}
}

测试结果

go test -bench=. -benchmem -run=none

goos: darwin
goarch: arm64
pkg: golang_benchmark/sync_pool
BenchmarkBufferWithPool-8        8709889               138.9 ns/op             0 B/op          0 allocs/op
BenchmarkBufferWithoutPool-8     1862120               634.4 ns/op         10240 B/op          1 allocs/op
PASS
ok      golang_benchmark/sync_pool      4.707s

测试结论

  • 若对象要被反复使用,sync.Pool能显著提升性能,减少GC