var studentPool = sync.Pool{ New: func()interface{} { returnnew(Student) }, }
2.2 Get & Put
1 2 3
stu := studentPool.Get().(*Student) json.Unmarshal(buf, stu) studentPool.Put(stu)
Get() 用于从对象池中获取对象,因为返回值是 interface{},因此需要类型转换。
Put() 则是在对象使用完毕后,返回对象池。
3 性能测试
3.1 struct 反序列化
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcBenchmarkUnmarshal(b *testing.B) { for n := 0; n < b.N; n++ { stu := &Student{} json.Unmarshal(buf, stu) } }
funcBenchmarkUnmarshalWithPool(b *testing.B) { for n := 0; n < b.N; n++ { stu := studentPool.Get().(*Student) json.Unmarshal(buf, stu) studentPool.Put(stu) } }
测试结果如下:
1 2 3 4 5 6 7 8
$ go test -bench . -benchmem goos: darwin goarch: amd64 pkg: example/hpg-sync-pool BenchmarkUnmarshal-8 1993 559768 ns/op 5096 B/op 7 allocs/op BenchmarkUnmarshalWithPool-8 1976 550223 ns/op 234 B/op 6 allocs/op PASS ok example/hpg-sync-pool 2.334s
funcFprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { p := newPrinter() p.doPrintf(format, a) n, err = w.Write(p.buf) p.free() return }
// Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. funcPrintf(format string, a ...interface{}) (n int, err error) { return Fprintf(os.Stdout, format, a...) }