From e00da2ac657e73d44e9822a72e943a24d70cbaac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Fri, 9 Feb 2024 14:40:44 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=91=E2=80=8D=F0=9F=92=BB=20ToString:?= =?UTF-8?q?=20improve=20test=20and=20bench=20setup=20-=20sequential=20and?= =?UTF-8?q?=20parallel=20benchmark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- convert_test.go | 63 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/convert_test.go b/convert_test.go index 7d0f839..622412a 100644 --- a/convert_test.go +++ b/convert_test.go @@ -12,6 +12,33 @@ import ( "github.com/stretchr/testify/require" ) +var dataTypeExamples []interface{} + +func init() { + dataTypeExamples = []interface{}{ + 42, + int8(42), + int16(42), + int32(42), + int64(42), + uint(42), + uint8(42), + uint16(42), + uint32(42), + uint64(42), + "Hello, World!", + []byte("Hello, World!"), + true, + float32(3.14), + float64(3.14), + time.Now(), + []string{"Hello", "World"}, + []int{42, 21}, + [2]int{42, 21}, + []interface{}{[]int{42, 21}, 42, "Hello", true, []string{"Hello", "World"}}, + } +} + func Test_UnsafeString(t *testing.T) { t.Parallel() res := UnsafeString([]byte("Hello, World!")) @@ -127,31 +154,23 @@ func Test_ToString(t *testing.T) { // go test -v -run=^$ -bench=ToString -benchmem -count=4 func Benchmark_ToString(b *testing.B) { - values := []interface{}{ - 42, - int8(42), - int16(42), - int32(42), - int64(42), - uint(42), - uint8(42), - uint16(42), - uint32(42), - uint64(42), - "Hello, World!", - []byte("Hello, World!"), - true, - float32(3.14), - float64(3.14), - time.Now(), - []string{"Hello", "World"}, - []int{42, 21}, - [2]int{42, 21}, - []interface{}{[]int{42, 21}, 42, "Hello", true, []string{"Hello", "World"}}, + for _, value := range dataTypeExamples { + b.Run(reflect.TypeOf(value).String(), func(b *testing.B) { + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + _ = ToString(value) + } + }) } - for _, value := range values { +} + +// go test -v -run=^$ -bench=ToString_concurrency -benchmem -count=4 +func Benchmark_ToString_concurrency(b *testing.B) { + for _, value := range dataTypeExamples { b.Run(reflect.TypeOf(value).String(), func(b *testing.B) { b.ReportAllocs() + b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { _ = ToString(value)