mirror of
https://github.com/golang/go.git
synced 2025-10-19 11:03:18 +00:00
optimize errors.Join for single unwrappable errors
This commit is contained in:
parent
a9922d096f
commit
e5ad8fdb80
2 changed files with 46 additions and 0 deletions
|
@ -26,6 +26,18 @@ func Join(errs ...error) error {
|
|||
if n == 0 {
|
||||
return nil
|
||||
}
|
||||
if n == 1 {
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
if _, ok := err.(interface {
|
||||
Unwrap() []error
|
||||
}); ok {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
e := &joinError{
|
||||
errs: make([]error, 0, n),
|
||||
}
|
||||
|
|
|
@ -70,3 +70,37 @@ func TestJoinErrorMethod(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkJoin(b *testing.B) {
|
||||
for _, bb := range []struct {
|
||||
name string
|
||||
errs []error
|
||||
}{
|
||||
{
|
||||
name: "no error",
|
||||
},
|
||||
{
|
||||
name: "single non-nil error",
|
||||
errs: []error{errors.New("err")},
|
||||
},
|
||||
{
|
||||
name: "multiple errors",
|
||||
errs: []error{errors.New("err"), errors.New("newerr"), errors.New("newerr2")},
|
||||
},
|
||||
{
|
||||
name: "unwrappable single error",
|
||||
errs: []error{errors.Join(errors.New("err"))},
|
||||
},
|
||||
{
|
||||
name: "nil first error",
|
||||
errs: []error{nil, errors.New("newerr")},
|
||||
},
|
||||
} {
|
||||
b.Run(bb.name, func(b *testing.B) {
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = errors.Join(bb.errs...)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue