Skip to content

Commit c5ed378

Browse files
committed
add benchmark for SliceToString
1 parent 7ba3478 commit c5ed378

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

stringutils_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package stringutils
22

33
import (
4+
"fmt"
45
"testing"
56

67
"github.com/stretchr/testify/assert"
@@ -176,3 +177,47 @@ func TestHasSuffixSlice(t *testing.T) {
176177
})
177178
}
178179
}
180+
181+
func BenchmarkSliceToString(b *testing.B) {
182+
tmpl := []any{[]byte("fdjndfg")}
183+
b.Run("unsafe (small slice)", func(b *testing.B) {
184+
for i := 0; i < b.N; i++ {
185+
SliceToString(tmpl)
186+
}
187+
})
188+
b.Run("type assert (small slice)", func(b *testing.B) {
189+
for i := 0; i < b.N; i++ {
190+
sliceToStringAllocs(tmpl)
191+
}
192+
})
193+
194+
for i := 0; i < 20; i++ {
195+
tmpl = append(tmpl, tmpl...)
196+
}
197+
198+
b.Run("unsafe (big slice)", func(b *testing.B) {
199+
for i := 0; i < b.N; i++ {
200+
SliceToString(tmpl)
201+
}
202+
})
203+
b.Run("type assert (big slice)", func(b *testing.B) {
204+
for i := 0; i < b.N; i++ {
205+
sliceToStringAllocs(tmpl)
206+
}
207+
})
208+
}
209+
210+
func sliceToStringAllocs(s []any) []string {
211+
if len(s) == 0 {
212+
return nil
213+
}
214+
strSlice := make([]string, len(s))
215+
for i, v := range s {
216+
if vb, ok := v.([]byte); ok {
217+
strSlice[i] = string(vb)
218+
continue
219+
}
220+
strSlice[i] = fmt.Sprintf("%v", v)
221+
}
222+
return strSlice
223+
}

0 commit comments

Comments
 (0)