From c50301e942eb86ce46f1d5bcf5c8a65c175e937b Mon Sep 17 00:00:00 2001 From: Jeremy Quirke Date: Fri, 18 Aug 2023 16:42:31 -0700 Subject: [PATCH] Add benchmarks for chained Withs (#1326) Add benchmarks to show the performance of chaining child loggers via 'With' and whether the logger is used or not used. This is intended to establish a baseline for a proposed optimisation in PR https://github.com/uber-go/zap/pull/1319. --- logger_bench_test.go | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/logger_bench_test.go b/logger_bench_test.go index bcf501a3f..c7207afd5 100644 --- a/logger_bench_test.go +++ b/logger_bench_test.go @@ -23,6 +23,7 @@ package zap import ( "errors" "runtime" + "strconv" "sync" "testing" "time" @@ -198,6 +199,37 @@ func BenchmarkAddCallerAndStacktrace(b *testing.B) { } }) } +func Benchmark5WithsUsed(b *testing.B) { + benchmarkWithUsed(b, 5, true) +} + +// This benchmark will be used in future as a +// baseline for improving +func Benchmark5WithsNotUsed(b *testing.B) { + benchmarkWithUsed(b, 5, false) +} + +func benchmarkWithUsed(b *testing.B, N int, use bool) { + keys := make([]string, N) + values := make([]string, N) + for i := 0; i < N; i++ { + keys[i] = "k" + strconv.Itoa(i) + values[i] = "v" + strconv.Itoa(i) + } + + b.ResetTimer() + + withBenchedLogger(b, func(log *Logger) { + for i := 0; i < N; i++ { + log = log.With(String(keys[i], values[i])) + } + if use { + log.Info("used") + return + } + runtime.KeepAlive(log) + }) +} func Benchmark10Fields(b *testing.B) { withBenchedLogger(b, func(log *Logger) {