Skip to content

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

Closed

Description

@egonelbre

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.

Activity

  1. added
    type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.
    priority: p2Moderately-important priority. Fix may not be included in next release.
    on Apr 11, 2024
  2. codyoss commented on Apr 11, 2024

    @codyoss
    Member

    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.

  3. quartzmo commented on Aug 12, 2024

    @quartzmo
    Member

    @codyoss Can this be closed now?

  4. egonelbre commented on Aug 13, 2024

    @egonelbre
    ContributorAuthor

    There are still 137 cases of fmt.Errorf being used in the repo. This can be easily seen by running gofmt -w -r "fmt.Errorf(s) -> errors.New(s)" on the whole repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ 换网址