Skip to content

Commit aa3e272

Browse files
Tweak benchmarks
1 parent 934e7cc commit aa3e272

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

log_test.go

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -267,33 +267,41 @@ func TestContext(t *testing.T) {
267267
func BenchmarkLogger(b *testing.B) {
268268
hue.Enabled(true) // Force colour
269269

270-
b.Run("enabled", func(b *testing.B) {
271-
buf := &bytes.Buffer{}
270+
// Declare the buffer out here otherwise the benchmarks
271+
// pick up the growing and re-allocating of this buffer
272+
// which is just an artifact of the benchmark
273+
buf := &bytes.Buffer{}
272274

273-
logger := log.New(buf, log.WithLevel(log.LevelDebug))
275+
// Likewise the loggers are declared out here because creating the logger
276+
// is typically done once in an application and the logger is re-used a bunch
277+
// of times to write log lines
278+
debugLogger := log.New(buf, log.WithLevel(log.LevelDebug))
279+
infoLogger := log.New(buf, log.WithLevel(log.LevelInfo))
280+
discardLogger := log.New(io.Discard, log.WithLevel(log.LevelDebug))
274281

282+
b.Run("enabled", func(b *testing.B) {
275283
for b.Loop() {
276-
logger.Debug("A message!")
284+
debugLogger.Debug("A message!")
277285
}
286+
287+
buf.Reset()
278288
})
279289

280290
b.Run("disabled", func(b *testing.B) {
281-
buf := &bytes.Buffer{}
282-
283-
logger := log.New(buf, log.WithLevel(log.LevelInfo))
284-
285291
for b.Loop() {
286-
logger.Debug("A message!")
292+
infoLogger.Debug("A message!")
287293
}
294+
295+
buf.Reset()
288296
})
289297

290298
b.Run("discard", func(b *testing.B) {
291299
// Here to test that effectively nothing is done
292300
// when w == io.Discard
293-
logger := log.New(io.Discard, log.WithLevel(log.LevelDebug))
294-
295301
for b.Loop() {
296-
logger.Debug("Nothing")
302+
discardLogger.Debug("Nothing")
297303
}
304+
305+
buf.Reset()
298306
})
299307
}

0 commit comments

Comments
 (0)