diff --git a/logger_bench_test.go b/logger_bench_test.go index 41e661577..bcf501a3f 100644 --- a/logger_bench_test.go +++ b/logger_bench_test.go @@ -22,6 +22,8 @@ package zap import ( "errors" + "runtime" + "sync" "testing" "time" @@ -238,3 +240,79 @@ func Benchmark100Fields(b *testing.B) { logger.With(first...).Info("Child loggers with lots of context.", second...) } } + +func BenchmarkAny(b *testing.B) { + key := "some-long-string-longer-than-16" + + tests := []struct { + name string + typed func() Field + anyArg any + }{ + { + name: "string", + typed: func() Field { return String(key, "yet-another-long-string") }, + anyArg: "yet-another-long-string", + }, + { + name: "stringer", + typed: func() Field { return Stringer(key, InfoLevel) }, + anyArg: InfoLevel, + }, + } + + for _, tt := range tests { + b.Run(tt.name, func(b *testing.B) { + b.Run("field-only", func(b *testing.B) { + b.Run("typed", func(b *testing.B) { + withBenchedLogger(b, func(log *Logger) { + f := tt.typed() + runtime.KeepAlive(f) + }) + }) + b.Run("any", func(b *testing.B) { + withBenchedLogger(b, func(log *Logger) { + f := Any(key, tt.anyArg) + runtime.KeepAlive(f) + }) + }) + }) + b.Run("log", func(b *testing.B) { + b.Run("typed", func(b *testing.B) { + withBenchedLogger(b, func(log *Logger) { + log.Info("", tt.typed()) + }) + }) + b.Run("any", func(b *testing.B) { + withBenchedLogger(b, func(log *Logger) { + log.Info("", Any(key, tt.anyArg)) + }) + }) + }) + b.Run("log-go", func(b *testing.B) { + b.Run("typed", func(b *testing.B) { + withBenchedLogger(b, func(log *Logger) { + var wg sync.WaitGroup + wg.Add(1) + go func() { + log.Info("", tt.typed()) + wg.Done() + }() + wg.Wait() + }) + }) + b.Run("any", func(b *testing.B) { + withBenchedLogger(b, func(log *Logger) { + var wg sync.WaitGroup + wg.Add(1) + go func() { + log.Info("", Any(key, tt.anyArg)) + wg.Done() + }() + wg.Wait() + }) + }) + }) + }) + } +}