diff --git a/binary/writer.go b/binary/writer.go index 33e488d0..86742eba 100644 --- a/binary/writer.go +++ b/binary/writer.go @@ -4,12 +4,12 @@ import ( "bytes" "encoding/binary" "encoding/hex" + "sync" ) type Writer bytes.Buffer -/* -var bufferPool = sync.Pool{ // todo sync.Pool 无法通过单元测试 +var bufferPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, @@ -27,7 +27,6 @@ func PutBuffer(buf *bytes.Buffer) { bufferPool.Put(buf) } } -*/ func NewWriter() *Writer { return new(Writer) @@ -40,9 +39,11 @@ func PutWriter(w *Writer) { */ func NewWriterF(f func(writer *Writer)) []byte { - w := new(bytes.Buffer) + w := NewBuffer() f((*Writer)(w)) - return w.Bytes() + b := append([]byte(nil), w.Bytes()...) + PutBuffer(w) + return b } func (w *Writer) Write(b []byte) { diff --git a/binary/writer_test.go b/binary/writer_test.go index a62fb674..5c42d7bf 100644 --- a/binary/writer_test.go +++ b/binary/writer_test.go @@ -10,8 +10,8 @@ import ( ) func NewWriterFOld(f func(writer *Writer)) []byte { - w := (*Writer)(new(bytes.Buffer)) - f(w) + w := new(bytes.Buffer) + f((*Writer)(w)) return w.Bytes() } @@ -53,8 +53,8 @@ func TestNewWriterF(t *testing.T) { wg.Wait() } -func BenchmarkNewWriterFOld256(b *testing.B) { - test := make([]byte, 256) +func BenchmarkNewWriterFOld128(b *testing.B) { + test := make([]byte, 128) rand.Read(test) b.StartTimer() b.RunParallel(func(pb *testing.PB) { @@ -66,8 +66,8 @@ func BenchmarkNewWriterFOld256(b *testing.B) { }) } -func BenchmarkNewWriterF256(b *testing.B) { - test := make([]byte, 256) +func BenchmarkNewWriterF128(b *testing.B) { + test := make([]byte, 128) rand.Read(test) b.StartTimer() b.RunParallel(func(pb *testing.PB) { @@ -79,27 +79,31 @@ func BenchmarkNewWriterF256(b *testing.B) { }) } -func BenchmarkNewWriterFOld1024(b *testing.B) { - test := make([]byte, 1024) +func BenchmarkNewWriterFOld128_3(b *testing.B) { + test := make([]byte, 128) rand.Read(test) b.StartTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { NewWriterFOld(func(w *Writer) { w.Write(test) + w.Write(test) + w.Write(test) }) } }) } -func BenchmarkNewWriterF1024(b *testing.B) { - test := make([]byte, 1024) +func BenchmarkNewWriterF128_3(b *testing.B) { + test := make([]byte, 128) rand.Read(test) b.StartTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { NewWriterF(func(w *Writer) { w.Write(test) + w.Write(test) + w.Write(test) }) } })