Skip to content

Instantly share code, notes, and snippets.

@djoreilly
Forked from 0xc0d/poolBench_test.go
Last active September 14, 2023 10:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djoreilly/074fe4e4fabece4321158debe71dcd7d to your computer and use it in GitHub Desktop.
Save djoreilly/074fe4e4fabece4321158debe71dcd7d to your computer and use it in GitHub Desktop.
sync.Pool Benchmark test
// go test -bench=.
package main
import (
"sync"
"testing"
)
type Person struct {
Age int
}
var personPool = sync.Pool{
New: func() interface{} { return new(Person) },
}
func BenchmarkWithoutPool(b *testing.B) {
var p *Person
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 10000; j++ {
p = new(Person)
p.Age = 23
}
}
}
func BenchmarkWithPool(b *testing.B) {
var p *Person
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 0; j < 10000; j++ {
p = personPool.Get().(*Person)
p.Age = 23
personPool.Put(p)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment