stack_test.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package xerrors_test
  5. import (
  6. "bytes"
  7. "fmt"
  8. "math/big"
  9. "testing"
  10. "golang.org/x/xerrors"
  11. "golang.org/x/xerrors/internal"
  12. )
  13. type myType struct{}
  14. func (myType) Format(s fmt.State, v rune) {
  15. s.Write(bytes.Repeat([]byte("Hi! "), 10))
  16. }
  17. func BenchmarkErrorf(b *testing.B) {
  18. err := xerrors.New("foo")
  19. // pi := big.NewFloat(3.14) // Something expensive.
  20. num := big.NewInt(5)
  21. args := func(a ...interface{}) []interface{} { return a }
  22. benchCases := []struct {
  23. name string
  24. format string
  25. args []interface{}
  26. }{
  27. {"no_format", "msg: %v", args(err)},
  28. {"with_format", "failed %d times: %v", args(5, err)},
  29. {"method: mytype", "pi: %v", args("myfile.go", myType{}, err)},
  30. {"method: number", "pi: %v", args("myfile.go", num, err)},
  31. }
  32. for _, bc := range benchCases {
  33. b.Run(bc.name, func(b *testing.B) {
  34. b.Run("ExpWithTrace", func(b *testing.B) {
  35. for i := 0; i < b.N; i++ {
  36. xerrors.Errorf(bc.format, bc.args...)
  37. }
  38. })
  39. b.Run("ExpNoTrace", func(b *testing.B) {
  40. internal.EnableTrace = false
  41. defer func() { internal.EnableTrace = true }()
  42. for i := 0; i < b.N; i++ {
  43. xerrors.Errorf(bc.format, bc.args...)
  44. }
  45. })
  46. b.Run("Core", func(b *testing.B) {
  47. for i := 0; i < b.N; i++ {
  48. fmt.Errorf(bc.format, bc.args...)
  49. }
  50. })
  51. })
  52. }
  53. }