Skip to content
Myr

improve sliceValidateError.Error performance using switch and strings.Builder (#2765)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

fix missing nil pointer check use simpler switch case add missing tests use for-loop instead of range add benchmark test codes

authored by ziheng · committed by GitHub · parent 1d0f938 · Browse files · 3 files+58 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+58 added−6 removed

  • other:+58 added−6 removed

3 files+58 added−6 removed

added:binding/default_validator_benchmark_test.go+20 added
1package binding23import (4 "errors"5 "strconv"6 "testing"7)89func BenchmarkSliceValidateError(b *testing.B) {10 const size int = 10011 for i := 0; i < b.N; i++ {12 e := make(sliceValidateError, size)13 for j := 0; j < size; j++ {14 e[j] = errors.New(strconv.Itoa(j))15 }16 if len(e.Error()) == 0 {17 b.Errorf("error")18 }19 }20}
modified:binding/default_validator_test.go+20 added
14 unmodified lines
15 err sliceValidateError16 want string17 }{18 {"has nil elements", sliceValidateError{errors.New("test error"), nil}, "[0]: test error"},19 {"has zero elements", sliceValidateError{}, ""},20 {"has one element", sliceValidateError{errors.New("test one error")}, "[0]: test one error"},21 {"has two elements",22 sliceValidateError{23 errors.New("first error"),24 errors.New("second error"),25 },26 "[0]: first error\n[1]: second error",27 },28 {"has many elements",29 sliceValidateError{30 errors.New("first error"),31 errors.New("second error"),32 nil,33 nil,34 nil,35 errors.New("last error"),36 },37 "[0]: first error\n[1]: second error\n[5]: last error",38 },39 }40 for _, tt := range tests {41 t.Run(tt.name, func(t *testing.T) {42 if got := tt.err.Error(); got != tt.want {
46 unmodified lines
modified:binding/default_validator.go+18 added-6 removed
18 unmodified lines
19}2021type sliceValidateError []error2223// Error concatenates all error elements in sliceValidateError into a single string separated by \n.24func (err sliceValidateError) Error() string {24 var errMsgs []string25 for i, e := range err {26 if e == nil {27 continue25 n := len(err)26 switch n {27 case 0:28 return ""29 default:30 var b strings.Builder31 if err[0] != nil {32 fmt.Fprintf(&b, "[%d]: %s", 0, err[0].Error())33 }29 errMsgs = append(errMsgs, fmt.Sprintf("[%d]: %s", i, e.Error()))34 if n > 1 {35 for i := 1; i < n; i++ {36 if err[i] != nil {37 b.WriteString("\n")38 fmt.Fprintf(&b, "[%d]: %s", i, err[i].Error())39 }40 }41 }42 return b.String()43 }31 return strings.Join(errMsgs, "\n")44}4546var _ StructValidator = &defaultValidator{}47
50 unmodified lines