]> Cypherpunks repositories - gostls13.git/commitdiff
log/slog: use plain string concatenation for Attr.String
authorKevin Burke <kevin@burke.dev>
Thu, 21 Mar 2024 22:59:30 +0000 (15:59 -0700)
committerGopher Robot <gobot@golang.org>
Mon, 25 Mar 2024 18:23:25 +0000 (18:23 +0000)
Plain string concatenation with the plus operator for Attr.String is
much faster than invoking fmt.Sprintf. Added a benchmark to verify
this (just running on my Mac with stuff in the background but should
be sufficient to demonstrate the effect).

name          old time/op  new time/op  delta
AttrString-8  1.24µs ± 3%  0.43µs ± 0%  -65.17%  (p=0.000 n=20+17)

name          old alloc/op   new alloc/op   delta
AttrString-8      432B ± 0%      152B ± 0%   ~     (p=1.000 n=1+1)

name          old allocs/op  new allocs/op  delta
AttrString-8      30.0 ± 0%      16.0 ± 0%   ~     (p=1.000 n=1+1)

Change-Id: I18ac91cbff1047d168b51a595601e36b5f676615
Reviewed-on: https://go-review.googlesource.com/c/go/+/573517
Reviewed-by: David Chase <drchase@google.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Run-TryBot: Emmanuel Odeke <emmanuel@orijtech.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Emmanuel Odeke <emmanuel@orijtech.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
TryBot-Result: Gopher Robot <gobot@golang.org>

src/log/slog/attr.go
src/log/slog/attr_test.go

index 2f459467cb6f2888b68a9404f6bd6b04ae10e017..067c537cc973fc2b788c0c4449894ec326f830f3 100644 (file)
@@ -5,7 +5,6 @@
 package slog
 
 import (
-       "fmt"
        "time"
 )
 
@@ -92,7 +91,7 @@ func (a Attr) Equal(b Attr) bool {
 }
 
 func (a Attr) String() string {
-       return fmt.Sprintf("%s=%s", a.Key, a.Value)
+       return a.Key + "=" + a.Value.String()
 }
 
 // isEmpty reports whether a has an empty key and a nil value.
index 1187a856fd354af851d9dd026773baf4199de938..e01447cfedd19e5652e878796ab4fe244e838e8c 100644 (file)
@@ -41,3 +41,34 @@ func TestAttrNoAlloc(t *testing.T) {
        _ = s
        _ = x
 }
+
+func BenchmarkAttrString(b *testing.B) {
+       var (
+               is string
+               u  string
+               f  string
+               bn string
+               s  string
+               x  string
+               ds string
+               p  = &is
+               d  time.Duration
+       )
+       b.ReportAllocs()
+       for i := 0; i < b.N; i++ {
+               is = Int64("key", 1).String()
+               u = Uint64("key", 1).String()
+               f = Float64("key", 1).String()
+               bn = Bool("key", true).String()
+               s = String("key", "foo").String()
+               ds = Duration("key", d).String()
+               x = Any("key", p).String()
+       }
+       _ = u
+       _ = f
+       _ = bn
+       _ = s
+       _ = x
+       _ = ds
+       _ = p
+}