github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/perf/bbp/buffer_test.go (about) 1 package bbp 2 3 import ( 4 "bytes" 5 "strings" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestBufferReadFrom(t *testing.T) { 12 str := strings.Repeat("hello world", 1<<18) 13 buf := NewBuffer(0) 14 n, err := buf.ReadFrom(strings.NewReader(str)) 15 assert.Nil(t, err) 16 assert.Equal(t, 11*(1<<18), int(n)) 17 assert.Equal(t, str, buf.String()) 18 assert.Equal(t, str, buf.StringUnsafe()) 19 } 20 21 func TestBufferWrite(t *testing.T) { 22 str := "abc" 23 want := "" 24 var buf Buffer 25 for i := 0; i < 1000; i++ { 26 tmp := strings.Repeat(str, i) 27 want += tmp 28 buf.WriteString(tmp) 29 } 30 got := buf.String() 31 assert.Equal(t, want, got) 32 } 33 34 func TestBufferWriteStrings(t *testing.T) { 35 strs := []string{ 36 "hello ", 37 "world", 38 } 39 for i := 0; i < 18; i++ { // -> 2_883_584 40 strs = append(strs, strs...) 41 } 42 buf := NewBuffer(0) 43 buf.WriteStrings(strs) 44 want := strings.Repeat("hello world", 1<<18) 45 assert.Equal(t, want, buf.String()) 46 } 47 48 func BenchmarkBufferWrite(b *testing.B) { 49 s := []byte("foobarbaz") 50 b.ReportAllocs() 51 b.RunParallel(func(pb *testing.PB) { 52 var buf Buffer 53 for pb.Next() { 54 for i := 0; i < 100; i++ { 55 buf.Write(s) 56 } 57 buf.Reset() 58 } 59 }) 60 } 61 62 func BenchmarkBytesBufferWrite(b *testing.B) { 63 s := []byte("foobarbaz") 64 b.ReportAllocs() 65 b.RunParallel(func(pb *testing.PB) { 66 var buf bytes.Buffer 67 for pb.Next() { 68 for i := 0; i < 100; i++ { 69 buf.Write(s) 70 } 71 buf.Reset() 72 } 73 }) 74 }