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

Conversation

manisharma
Copy link

Proposing to use strings.Builder in place of string concatenation, in battery.Error() - following are the results -

╭─[email protected] ~/workspace/battery  ‹master› 
╰─➤  go test -bench=. -benchtime 2s -count 1 -benchmem -cpu 4 -run notest
goos: darwin
goarch: arm64
pkg: github.com/distatus/battery
BenchmarkErrors_Error-4                 14642497               147.5 ns/op            64 B/op          6 allocs/op
BenchmarkErrors_ErrorBuilder-4          37910373                63.16 ns/op           24 B/op          2 allocs/op
PASS
ok      github.com/distatus/battery     4.896s

Copy link
Member

@KenjiTakahashi KenjiTakahashi left a comment

Choose a reason for hiding this comment

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

Thanks, makes perfect sense to change that. The strings.Builder didn't exist back when I was writing this code.

No need to include 2 versions and benchmarks, though, we're not a strings building library ;-). Just change the old implementation to the new one.

@manisharma
Copy link
Author

Thanks, makes perfect sense to change that. The strings.Builder didn't exist back when I was writing this code.

No need to include 2 versions and benchmarks, though, we're not a strings building library ;-). Just change the old implementation to the new one.

Done, thanks!

if err != nil {
s += err.Error() + " "
if idx >= 1 {
Copy link
Member

Choose a reason for hiding this comment

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

Now it has the same problem with nil at the beginning ;-].
You cannot rely on indexes when you're also filtering at the same time.
Think the way to solve it here is to check s.Len() > 1. Shouldn't add much to the time, as the Len call is effectively O(1).

if err != nil {
s += err.Error() + " "
if idx >= 1 {
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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants