]> Cypherpunks repositories - gostls13.git/commitdiff
log/slog: optimize slog Level.String() to avoid fmt.Sprintf
authormohanson <mohanson@outlook.com>
Thu, 18 Sep 2025 03:42:30 +0000 (11:42 +0800)
committerGopher Robot <gobot@golang.org>
Fri, 19 Sep 2025 16:59:42 +0000 (09:59 -0700)
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 <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Sean Liao <sean@liao.dev>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Auto-Submit: Emmanuel Odeke <emmanuel@orijtech.com>
Reviewed-by: Michael Knyszek <mknyszek@google.com>
src/log/slog/level.go
src/log/slog/level_test.go

index 2957585e0e848c69e4cae724647f4dcbbb3c360a..9e812eb165b40a99d55948acda635fcea9fcfd27 100644 (file)
@@ -61,7 +61,11 @@ func (l Level) String() string {
                if val == 0 {
                        return base
                }
-               return fmt.Sprintf("%s%+d", base, val)
+               sval := strconv.Itoa(int(val))
+               if val > 0 {
+                       sval = "+" + sval
+               }
+               return base + sval
        }
 
        switch {
index 73be1126b275dc62e3bc7f905a9b7827dc92b928..c9a1c16c0362556d8857c19afa8737fc6a10c1a0 100644 (file)
@@ -215,3 +215,25 @@ func TestLevelVarString(t *testing.T) {
                t.Errorf("got %q, want %q", got, want)
        }
 }
+
+func BenchmarkLevelString(b *testing.B) {
+       levels := []Level{
+               0,
+               LevelError,
+               LevelError + 2,
+               LevelError - 2,
+               LevelWarn,
+               LevelWarn - 1,
+               LevelInfo,
+               LevelInfo + 1,
+               LevelInfo - 3,
+               LevelDebug,
+               LevelDebug - 2,
+       }
+       b.ResetTimer()
+       for b.Loop() {
+               for _, level := range levels {
+                       _ = level.String()
+               }
+       }
+}