| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package errors_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
fmtcore "fmt" |
| 10 |
"math/big" |
| 11 |
"testing" |
| 12 |
|
| 13 |
"golang.org/x/exp/errors" |
| 14 |
"golang.org/x/exp/errors/fmt" |
| 15 |
"golang.org/x/exp/errors/internal" |
| 16 |
) |
| 17 |
|
| 18 |
type myType struct{} |
| 19 |
|
| 20 |
func (myType) Format(s fmt.State, v rune) { |
| 21 |
s.Write(bytes.Repeat([]byte("Hi! "), 10)) |
| 22 |
} |
| 23 |
|
| 24 |
func BenchmarkErrorf(b *testing.B) { |
| 25 |
err := errors.New("foo") |
| 26 |
|
| 27 |
num := big.NewInt(5) |
| 28 |
args := func(a ...interface{}) []interface{} { return a } |
| 29 |
benchCases := []struct { |
| 30 |
name string |
| 31 |
format string |
| 32 |
args []interface{} |
| 33 |
}{ |
| 34 |
{"no_format", "msg: %v", args(err)}, |
| 35 |
{"with_format", "failed %d times: %v", args(5, err)}, |
| 36 |
{"method: mytype", "pi: %v", args("myfile.go", myType{}, err)}, |
| 37 |
{"method: number", "pi: %v", args("myfile.go", num, err)}, |
| 38 |
} |
| 39 |
for _, bc := range benchCases { |
| 40 |
b.Run(bc.name, func(b *testing.B) { |
| 41 |
b.Run("ExpWithTrace", func(b *testing.B) { |
| 42 |
for i := 0; i < b.N; i++ { |
| 43 |
fmt.Errorf(bc.format, bc.args...) |
| 44 |
} |
| 45 |
}) |
| 46 |
b.Run("ExpNoTrace", func(b *testing.B) { |
| 47 |
internal.EnableTrace = false |
| 48 |
defer func() { internal.EnableTrace = true }() |
| 49 |
|
| 50 |
for i := 0; i < b.N; i++ { |
| 51 |
fmt.Errorf(bc.format, bc.args...) |
| 52 |
} |
| 53 |
}) |
| 54 |
b.Run("Core", func(b *testing.B) { |
| 55 |
for i := 0; i < b.N; i++ { |
| 56 |
fmtcore.Errorf(bc.format, bc.args...) |
| 57 |
} |
| 58 |
}) |
| 59 |
}) |
| 60 |
} |
| 61 |
} |