Skip to content

Commit 26fc4aa

Browse files
callthingsoffneild
authored andcommitted
errors: optimize *joinError's Error method for less allocation and faster execution
Handle the case of one error at the beginning. Use unsafe.String to avoid memory allocation when converting byte slice to string. Change-Id: Ib23576f72b1d87489e6f17762be483f62ca4998a GitHub-Last-Rev: ed8003b GitHub-Pull-Request: #60026 Reviewed-on: https://go-review.googlesource.com/c/go/+/493237 Reviewed-by: Damien Neil <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: David Chase <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent 17d67ed commit 26fc4aa

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

src/errors/join.go

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
package errors
66

7+
import (
8+
"unsafe"
9+
)
10+
711
// Join returns an error that wraps the given errors.
812
// Any nil error values are discarded.
913
// Join returns nil if every value in errs is nil.
@@ -38,14 +42,19 @@ type joinError struct {
3842
}
3943

4044
func (e *joinError) Error() string {
41-
var b []byte
42-
for i, err := range e.errs {
43-
if i > 0 {
44-
b = append(b, '\n')
45-
}
45+
// Since Join returns nil if every value in errs is nil,
46+
// e.errs cannot be empty.
47+
if len(e.errs) == 1 {
48+
return e.errs[0].Error()
49+
}
50+
51+
b := []byte(e.errs[0].Error())
52+
for _, err := range e.errs[1:] {
53+
b = append(b, '\n')
4654
b = append(b, err.Error()...)
4755
}
48-
return string(b)
56+
// At this point, b has at least one byte '\n'.
57+
return unsafe.String(&b[0], len(b))
4958
}
5059

5160
func (e *joinError) Unwrap() []error {

0 commit comments

Comments
 (0)