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

perf: fmt.Errorf used instead of errors.New #9749

Open
egonelbre opened this issue Apr 11, 2024 · 1 comment
Open

perf: fmt.Errorf used instead of errors.New #9749

egonelbre opened this issue Apr 11, 2024 · 1 comment
Labels
priority: p2 Moderately-important priority. Fix may not be included in next release. type: bug Error or flaw in code with unintended results or allowing sub-optimal usage patterns.

Comments

@egonelbre
Copy link
Contributor

Throughout the whole codebase there are many places that use fmt.Errorf whereas errors.New can be used. Using fmt.Errorf is roughly 4x slower than errors.New.

This can be easily benchmarked with:

var result error

func BenchmarkFmtError(b *testing.B) {
	for range b.N {
		result = fmt.Errorf("something")
	}
}

func BenchmarkErrorsNew(b *testing.B) {
	for range b.N {
		result = errors.New("something")
	}
}

On my computer I'm getting:

BenchmarkFmtError-32             9535638               123.8 ns/op            32 B/op          2 allocs/op
BenchmarkErrorsNew-32           32106765                33.87 ns/op           16 B/op          1 allocs/op

This performance issue can be automatically fixed with:

gofmt -w -r "fmt.Errorf(s) -> errors.New(s)" .

Those error paths usually aren't hot paths, however it might impact the size of code generated.

@codyoss codyoss added type: bug Error or flaw in code with unintended results or allowing sub-optimal usage patterns. priority: p2 Moderately-important priority. Fix may not be included in next release. labels Apr 11, 2024
@codyoss
Copy link
Member

codyoss commented Apr 11, 2024

Thanks for the detailed report. This is a good suggestion. It looks like a good number of these are in our generated code so we can patch our generator to remove a lot of these and gofmt the rest.

codyoss added a commit to codyoss/gapic-generator-go that referenced this issue Apr 11, 2024
codyoss added a commit to googleapis/gapic-generator-go that referenced this issue Apr 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
priority: p2 Moderately-important priority. Fix may not be included in next release. type: bug Error or flaw in code with unintended results or allowing sub-optimal usage patterns.
Projects
None yet
Development

No branches or pull requests

2 participants