Skip to content

Instantly share code, notes, and snippets.

@EagleChen
Created September 9, 2018 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EagleChen/5312514e084a353b75bbc15be75d3f45 to your computer and use it in GitHub Desktop.
Save EagleChen/5312514e084a353b75bbc15be75d3f45 to your computer and use it in GitHub Desktop.
benchmark different error creation methods
package main
import (
"errors"
"fmt"
"strconv"
"testing"
)
type MyError struct {
Err error
File string
Line int
Msg string
}
func (e MyError) Error() string {
return e.File + ":" + strconv.Itoa(e.Line) + ": " + e.Msg + " -- " + e.Err.Error()
}
func newError(file string, line int, msg string, err error) error {
return errors.New(file + ":" + strconv.Itoa(line) + ": " + msg + " -- " + err.Error())
}
func f(err error) {
err.Error()
}
func BenchmarkErrorF(b *testing.B) {
b.ReportAllocs()
err := errors.New("base")
for i := 0; i < 100000; i++ {
f(fmt.Errorf("%s:%d: %s %v", "test.go", 1, "wrapped error", err))
}
}
func BenchmarkErrorNew(b *testing.B) {
b.ReportAllocs()
err := errors.New("base")
for i := 0; i < 100000; i++ {
f(newError("test.go", 1, "wrapped error", err))
}
}
func BenchmarkErrorCustom(b *testing.B) {
b.ReportAllocs()
err := errors.New("base")
for i := 0; i < 100000; i++ {
f(MyError{Err: err, File: "abc", Line: 1, Msg: "wrapped error"})
}
}
/*
goos: darwin
goarch: amd64
BenchmarkErrorF-4 1000000000 0.03 ns/op 0 B/op 0 allocs/op
BenchmarkErrorNew-4 2000000000 0.00 ns/op 0 B/op 0 allocs/op
BenchmarkErrorCustom-4 2000000000 0.01 ns/op 0 B/op 0 allocs/op
PASS
ok _/private/tmp 0.316s
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment