Skip to content

Commit 8616981

Browse files
mohansongopherbot
authored andcommitted
log/slog: optimize slog Level.String() to avoid fmt.Sprintf
No more overhead of fmt.Sprintf, especially beneficial for high-frequency logging. goos: linux goarch: amd64 pkg: log/slog cpu: Intel(R) Xeon(R) Gold 6133 CPU @ 2.50GHz │ /tmp/old.txt │ /tmp/new.txt │ │ sec/op │ sec/op vs base │ LevelString-4 1006.5n ± 2% 334.2n ± 1% -66.80% (p=0.000 n=10) │ /tmp/old.txt │ /tmp/new.txt │ │ B/op │ B/op vs base │ LevelString-4 56.00 ± 0% 48.00 ± 0% -14.29% (p=0.000 n=10) │ /tmp/old.txt │ /tmp/new.txt │ │ allocs/op │ allocs/op vs base │ LevelString-4 7.000 ± 0% 7.000 ± 0% ~ (p=1.000 n=10) ¹ Change-Id: I6585d4aaa4da55d72ac70bc66dff45500eccd056 Reviewed-on: https://go-review.googlesource.com/c/go/+/704975 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Jonathan Amsterdam <[email protected]> Reviewed-by: Sean Liao <[email protected]> Reviewed-by: Emmanuel Odeke <[email protected]> Auto-Submit: Emmanuel Odeke <[email protected]> Reviewed-by: Michael Knyszek <[email protected]>
1 parent b8af744 commit 8616981

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/log/slog/level.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,11 @@ func (l Level) String() string {
6161
if val == 0 {
6262
return base
6363
}
64-
return fmt.Sprintf("%s%+d", base, val)
64+
sval := strconv.Itoa(int(val))
65+
if val > 0 {
66+
sval = "+" + sval
67+
}
68+
return base + sval
6569
}
6670

6771
switch {

src/log/slog/level_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,25 @@ func TestLevelVarString(t *testing.T) {
215215
t.Errorf("got %q, want %q", got, want)
216216
}
217217
}
218+
219+
func BenchmarkLevelString(b *testing.B) {
220+
levels := []Level{
221+
0,
222+
LevelError,
223+
LevelError + 2,
224+
LevelError - 2,
225+
LevelWarn,
226+
LevelWarn - 1,
227+
LevelInfo,
228+
LevelInfo + 1,
229+
LevelInfo - 3,
230+
LevelDebug,
231+
LevelDebug - 2,
232+
}
233+
b.ResetTimer()
234+
for b.Loop() {
235+
for _, level := range levels {
236+
_ = level.String()
237+
}
238+
}
239+
}

0 commit comments

Comments
 (0)