benchmarks_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package ut
  2. import (
  3. "testing"
  4. "github.com/go-playground/locales/en"
  5. )
  6. func BenchmarkBasicTranslation(b *testing.B) {
  7. en := en.New()
  8. ut := New(en, en)
  9. loc, found := ut.FindTranslator("en")
  10. if !found {
  11. b.Fatalf("Expected '%t' Got '%t'", true, found)
  12. }
  13. translations := []struct {
  14. key interface{}
  15. trans string
  16. expected error
  17. override bool
  18. }{
  19. {
  20. key: "welcome",
  21. trans: "Welcome to the site",
  22. expected: nil,
  23. },
  24. {
  25. key: "welcome-user",
  26. trans: "Welcome to the site {0}",
  27. expected: nil,
  28. },
  29. {
  30. key: "welcome-user2",
  31. trans: "Welcome to the site {0}, your location is {1}",
  32. expected: nil,
  33. },
  34. }
  35. for _, tt := range translations {
  36. if err := loc.Add(tt.key, tt.trans, tt.override); err != nil {
  37. b.Fatalf("adding translation '%s' failed with key '%s'", tt.trans, tt.key)
  38. }
  39. }
  40. var err error
  41. b.ResetTimer()
  42. b.Run("", func(b *testing.B) {
  43. for i := 0; i < b.N; i++ {
  44. if _, err = loc.T("welcome"); err != nil {
  45. b.Error(err)
  46. }
  47. }
  48. })
  49. b.Run("Parallel", func(b *testing.B) {
  50. b.RunParallel(func(pb *testing.PB) {
  51. for pb.Next() {
  52. if _, err = loc.T("welcome"); err != nil {
  53. b.Error(err)
  54. }
  55. }
  56. })
  57. })
  58. b.Run("With1Param", func(b *testing.B) {
  59. for i := 0; i < b.N; i++ {
  60. if _, err = loc.T("welcome-user", "Joeybloggs"); err != nil {
  61. b.Error(err)
  62. }
  63. }
  64. })
  65. b.Run("ParallelWith1Param", func(b *testing.B) {
  66. b.RunParallel(func(pb *testing.PB) {
  67. for pb.Next() {
  68. if _, err = loc.T("welcome-user", "Joeybloggs"); err != nil {
  69. b.Error(err)
  70. }
  71. }
  72. })
  73. })
  74. b.Run("With2Param", func(b *testing.B) {
  75. for i := 0; i < b.N; i++ {
  76. if _, err = loc.T("welcome-user2", "Joeybloggs", "/dev/tty0"); err != nil {
  77. b.Error(err)
  78. }
  79. }
  80. })
  81. b.Run("ParallelWith2Param", func(b *testing.B) {
  82. b.RunParallel(func(pb *testing.PB) {
  83. for pb.Next() {
  84. if _, err = loc.T("welcome-user2", "Joeybloggs", "/dev/tty0"); err != nil {
  85. b.Error(err)
  86. }
  87. }
  88. })
  89. })
  90. }