Skip to content

Commit

Permalink
optimize errors.Join for single errors that are already unwrappable
Browse files Browse the repository at this point in the history
  • Loading branch information
dmathieu committed Dec 11, 2024
1 parent a9922d0 commit 003cc98
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/errors/join.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand Down
34 changes: 34 additions & 0 deletions src/errors/join_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
}
})
}
}

0 comments on commit 003cc98

Please sign in to comment.