Skip to content

Commit d664cfd

Browse files
use string builder grow to reduce memory allocations in logging pkg
1 parent cb639b4 commit d664cfd

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

logging/logging.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ const (
3131

3232
var (
3333
DefaultDirName = filepath.Join("logs", "csp")
34+
35+
defaultLogMsgBufferSize = 256
3436
)
3537

3638
var (
@@ -117,6 +119,9 @@ func caller(depth int) (file string, line int) {
117119

118120
func AssembleMsg(depth int, logLevel, msg string, err error, keysAndValues ...interface{}) string {
119121
sb := strings.Builder{}
122+
if defaultLogMsgBufferSize > 0 {
123+
sb.Grow(defaultLogMsgBufferSize)
124+
}
120125
file, line := caller(depth)
121126
timeStr := time.Now().Format("2006-01-02 15:04:05.520")
122127
caller := fmt.Sprintf("%s:%d", file, line)

logging/logging_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,21 @@ func Benchmark_LoggingDebug_With_Precheck(b *testing.B) {
109109
}
110110
}
111111
}
112+
113+
func BenchmarkAssembleMsg(b *testing.B) {
114+
defaultLogMsgBufferSize = 256
115+
b.Run("assemble msg using string builder with grow", func(b *testing.B) {
116+
b.ReportAllocs()
117+
for i := 0; i < b.N; i++ {
118+
AssembleMsg(2, "INFO", "test msg", nil, "k1", "v1", "k2", "v2")
119+
}
120+
})
121+
122+
defaultLogMsgBufferSize = 0
123+
b.Run("assemble msg using string builder without grow", func(b *testing.B) {
124+
b.ReportAllocs()
125+
for i := 0; i < b.N; i++ {
126+
AssembleMsg(2, "INFO", "test msg", nil, "k1", "v1", "k2", "v2")
127+
}
128+
})
129+
}

0 commit comments

Comments
 (0)