bench_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package fserr
  2. import (
  3. "fmt"
  4. "testing"
  5. )
  6. // 针对于 New、Wrap 两种构建错误的方式进行性能测试对比,结果如下(堆栈深度为10、100、1000),golang版本1.22:
  7. // New
  8. // fserr
  9. // 801 ns/op
  10. // 1650 ns/op
  11. // 6262 ns/op
  12. //
  13. // Wrap
  14. // fserr
  15. // 826.2 ns/op
  16. // 1623 ns/op
  17. // 6201 ns/op
  18. //
  19. // WithCode
  20. // 2077 ns/op
  21. // 2765 ns/op
  22. // 7628 ns/op
  23. func yesErrors(at, depth int, how func() error) error {
  24. if at >= depth {
  25. return how()
  26. }
  27. return yesErrors(at+1, depth, how)
  28. }
  29. // GlobalE is an exported global to store the result of benchmark results,
  30. // preventing the compiler from optimising the benchmark functions away.
  31. var GlobalE interface{}
  32. func BenchmarkNew(b *testing.B) {
  33. for _, r := range []int{
  34. 10,
  35. 100,
  36. 1000,
  37. } {
  38. name := fmt.Sprintf("fserr-stack-%d", r)
  39. b.Run(name, func(b *testing.B) {
  40. var err error
  41. b.ReportAllocs()
  42. for i := 0; i < b.N; i++ {
  43. err = yesErrors(0, r, func() error {
  44. return New("success")
  45. })
  46. }
  47. b.StopTimer()
  48. GlobalE = err
  49. })
  50. }
  51. }
  52. func BenchmarkWrap(b *testing.B) {
  53. for _, r := range []int{
  54. 10,
  55. 100,
  56. 1000,
  57. } {
  58. name := fmt.Sprintf("fserr-stack-%d", r)
  59. b.Run(name, func(b *testing.B) {
  60. var err error
  61. b.ReportAllocs()
  62. for i := 0; i < b.N; i++ {
  63. err = yesErrors(0, r, func() error {
  64. return Wrap(New("origin"), "success")
  65. })
  66. }
  67. b.StopTimer()
  68. GlobalE = err
  69. })
  70. }
  71. }
  72. func BenchmarkWithCode(b *testing.B) {
  73. NewOK(ErrDb, "success")
  74. for _, r := range []int{
  75. 10,
  76. 100,
  77. 1000,
  78. } {
  79. name := fmt.Sprintf("fserr-stack-%d", r)
  80. b.Run(name, func(b *testing.B) {
  81. var err error
  82. b.ReportAllocs()
  83. for i := 0; i < b.N; i++ {
  84. err = yesErrors(0, r, func() error {
  85. return WithCode(nil, ErrDb)
  86. })
  87. }
  88. b.StopTimer()
  89. GlobalE = err
  90. })
  91. }
  92. }