File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 11package stringutils
22
33import (
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+ }
You can’t perform that action at this time.
0 commit comments