gitee.com/gricks/utils@v1.0.8/buffer_pool_test.go (about) 1 package utils 2 3 import ( 4 "bytes" 5 "strings" 6 "testing" 7 8 . "github.com/smartystreets/goconvey/convey" 9 ) 10 11 func Test_BufferWrites(t *testing.T) { 12 Convey("BufferWrite", t, func() { 13 buffer := NewBufferPool(1024).Get() 14 So(buffer.AppendByte('v').String(), ShouldEqual, "v") 15 buffer.Reset() 16 So(buffer.AppendString("foo").String(), ShouldEqual, "foo") 17 buffer.Reset() 18 So(buffer.AppendInt(43).String(), ShouldEqual, "43") 19 buffer.Reset() 20 So(buffer.AppendInt(-43).String(), ShouldEqual, "-43") 21 buffer.Reset() 22 So(buffer.AppendUint(43).String(), ShouldEqual, "43") 23 buffer.Reset() 24 So(buffer.AppendBool(true).String(), ShouldEqual, "true") 25 buffer.Reset() 26 So(buffer.AppendFloat32(float32(3.14)).String(), ShouldEqual, "3.14") 27 buffer.Reset() 28 So(buffer.AppendFloat64(float64(3.14)).String(), ShouldEqual, "3.14") 29 buffer.Reset() 30 buffer.Write([]byte("foo")) 31 So(buffer.String(), ShouldEqual, "foo") 32 }) 33 } 34 35 func BenchmarkBuffers(b *testing.B) { 36 // Because we use the strconv.AppendFoo functions so liberally, we can't 37 // use the standard library's bytes.Buffer anyways (without incurring a 38 // bunch of extra allocations). Nevertheless, let's make sure that we're 39 // not losing any precious nanoseconds. 40 str := strings.Repeat("a", 1024) 41 slice := make([]byte, 1024) 42 buf := bytes.NewBuffer(slice) 43 custom := NewBufferPool(1024).Get() 44 b.Run("ByteSlice", func(b *testing.B) { 45 for i := 0; i < b.N; i++ { 46 slice = append(slice, str...) 47 slice = slice[:0] 48 } 49 }) 50 b.Run("BytesBuffer", func(b *testing.B) { 51 for i := 0; i < b.N; i++ { 52 buf.WriteString(str) 53 buf.Reset() 54 } 55 }) 56 b.Run("CustomBuffer", func(b *testing.B) { 57 for i := 0; i < b.N; i++ { 58 custom.AppendString(str) 59 custom.Reset() 60 } 61 }) 62 }