From 7aabe92d75a140e18b6043d4cb70cbe34cefcd59 Mon Sep 17 00:00:00 2001 From: Oleg Zaytsev Date: Thu, 21 Feb 2019 09:49:45 +0100 Subject: [PATCH] Added NoDebugLogger that doesn't format debug logs fmt.Spritnf() is too expensive to call and debug logs are usually disabled in prod, so we don't want to waste time formatting them. --- no_debug_logger.go | 12 +++++++++ no_debug_logger_bench_test.go | 50 +++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 no_debug_logger.go create mode 100644 no_debug_logger_bench_test.go diff --git a/no_debug_logger.go b/no_debug_logger.go new file mode 100644 index 0000000..cdd7105 --- /dev/null +++ b/no_debug_logger.go @@ -0,0 +1,12 @@ +package log + +// NoDebugLogger embeds a Logger, but in calls to debug functions it does nothing. +// It avoids doing fmt.Sprintf() for those calls as they will be discarded anyways. +// This makes those calls like 50 times faster (see benchmark file) +type NoDebugLogger struct { + Logger +} + +func (NoDebugLogger) Debug(args ...interface{}) {} +func (NoDebugLogger) Debugf(format string, args ...interface{}) {} +func (NoDebugLogger) Debugln(args ...interface{}) {} \ No newline at end of file diff --git a/no_debug_logger_bench_test.go b/no_debug_logger_bench_test.go new file mode 100644 index 0000000..19988da --- /dev/null +++ b/no_debug_logger_bench_test.go @@ -0,0 +1,50 @@ +package log + +import ( + "testing" +) + +/* +$ go test -bench=. ./... + | goos: darwin + | goarch: amd64 + | pkg: github.com/cabify/go-logging + | BenchmarkPlainLoggerDebugSpeed-4 30000000 45.9 ns/op + | BenchmarkNoDebugLoggerDebugSpeed-4 2000000000 0.33 ns/op + | BenchmarkPlainLoggerDebugfSpeed-4 20000000 80.8 ns/op + | BenchmarkNoDebugLoggerDebugfSpeed-4 50000000 36.5 ns/op +*/ + +type someStruct struct { + value float64 +} + +var ( + structValue = someStruct{value: 10.0} + plainLoggerInstance = NewLogger("test") + noDebugLoggerInstance = NoDebugLogger{Logger: plainLoggerInstance} +) + +func BenchmarkPlainLoggerDebugSpeed(b *testing.B) { + for i := 0; i < b.N; i++ { + plainLoggerInstance.Debug("Something") + } +} + +func BenchmarkNoDebugLoggerDebugSpeed(b *testing.B) { + for i := 0; i < b.N; i++ { + noDebugLoggerInstance.Debug("Something") + } +} + +func BenchmarkPlainLoggerDebugfSpeed(b *testing.B) { + for i := 0; i < b.N; i++ { + plainLoggerInstance.Debugf("Something %v, %d", structValue, i) + } +} + +func BenchmarkNoDebugLoggerDebugfSpeed(b *testing.B) { + for i := 0; i < b.N; i++ { + noDebugLoggerInstance.Debugf("Something %v, %d", structValue, i) + } +}