Skip to content

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

@egonelbre

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.

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