Skip to content

Instantly share code, notes, and snippets.

@Deleplace
Created July 13, 2021 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deleplace/7b1d8798e64422926f5fc286674861a0 to your computer and use it in GitHub Desktop.
Save Deleplace/7b1d8798e64422926f5fc286674861a0 to your computer and use it in GitHub Desktop.
Benchmark for a Go proposal where a nil *log.Logger is a valid logger. This file works in the directory src/log/ .
package log
import (
"io"
"testing"
)
// New(io.Discard, "", 0) is the standard way of creating a
// disabled logger.
//
// l.SetOuput(io.Discard) is the standard way of disabling a
// logger l.
//
// They are expensive, as they actually compute the logs, holding
// a mutex locked, before discarding the logs.
func BenchmarkPrintfNumberDiscard(b *testing.B) {
logger := New(io.Discard, "", 0)
b.ResetTimer()
for i := 0; i < b.N; i++ {
n := i % 100
logger.Printf("n=%d", n)
}
}
func BenchmarkPrintfMapDiscard(b *testing.B) {
m := map[string]int{
"one": 1,
"two": 2,
}
logger := New(io.Discard, "", 0)
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Printf("x=%v", m)
}
}
// This is the proposed way of creating a disabled logger:
// use nil.
//
// These benchmarks are intended for a Go stdlib with
// log/log.go already patched (otherwise they will panic).
func BenchmarkPrintfNumberNil(b *testing.B) {
var logger *Logger = nil
b.ResetTimer()
for i := 0; i < b.N; i++ {
n := i % 100
logger.Printf("n=%d", n)
}
}
func BenchmarkPrintfMapNil(b *testing.B) {
m := map[string]int{
"one": 1,
"two": 2,
}
var logger *Logger = nil
b.ResetTimer()
for i := 0; i < b.N; i++ {
logger.Printf("x=%v", m)
}
}
@Deleplace
Copy link
Author

The proposal: golang/go#47164

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment