Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Errors() +performance : using strings.Builder instead of string concatenation #31

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@

package battery

import "fmt"
import (
"fmt"
"strings"
)

// ErrNotFound variable represents battery not found error.
//
Expand Down Expand Up @@ -130,6 +133,23 @@ func (e Errors) Error() string {
return s + "]"
}

func (e Errors) ErrorBuilder() string {
var s strings.Builder
s.WriteString("[")
for idx, err := range e {
if err != nil {
if idx == len(e)-1 {
s.Write([]byte(err.Error()))
} else {
s.WriteString(err.Error())
s.WriteString(" ")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose that WriteByte(' ') would be somewhat faster?

}
}
}
s.WriteString("]")
return s.String()
}

func wrapError(err error) error {
if perr, ok := err.(ErrPartial); ok {
if perr.isNil() {
Expand Down
26 changes: 26 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,29 @@ func TestErrors(t *testing.T) {
}
}
}

func BenchmarkErrors_Error(b *testing.B) {
e := getErrors()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = e.Error()
}
}

func BenchmarkErrors_ErrorBuilder(b *testing.B) {
e := getErrors()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = e.ErrorBuilder()
}
}

func getErrors() Errors {
return Errors([]error{
errors.New("1"),
errors.New("2"),
errors.New("3"),
errors.New("4"),
errors.New("5"),
})
}