From 65c53a1833a26467357b4aa6223e4dde5d6d7ed0 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Wed, 13 Sep 2023 22:26:19 +0000 Subject: [PATCH] log/slog: fix Record.back slice always too small during Add() When slog.Record.Add(args) is called, with enough args to cause the Record.back []Attr to be created, it is being created 1 too small, which results in it immediately being grown again by append before the function exits (needless allocation and copying). This is because it is created with a capacity equal to countAttrs(args), but forgets that there is an additional attribute to be appended: a (args is just the remaining unconsumed attributes). This PR fixes that by adding 1 to the capacity to account for the `a` attribute. Additionally, when Record.back already exists, it will most likely be at max capacity already. Rather than append to it and risk having it grown multiple times, or grow too large, this adds a slices.Grow call to set it to the right capacity, similar to what is already done in the Record.AddAttrs(attrs) function. Change-Id: Ic4bcf45909fe4436c586ccd2b8d61f24606b6be8 GitHub-Last-Rev: 4c924b610a7987a940360bb1b4cc7c53981afdc5 GitHub-Pull-Request: golang/go#62388 Reviewed-on: https://go-review.googlesource.com/c/go/+/524618 Reviewed-by: Jonathan Amsterdam LUCI-TryBot-Result: Go LUCI Reviewed-by: Heschi Kreinick --- src/log/slog/logger_test.go | 2 +- src/log/slog/record.go | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/log/slog/logger_test.go b/src/log/slog/logger_test.go index 17bdff2ba5..26e6f68f49 100644 --- a/src/log/slog/logger_test.go +++ b/src/log/slog/logger_test.go @@ -276,7 +276,7 @@ func TestAlloc(t *testing.T) { s := "abc" i := 2000 d := time.Second - wantAllocs(t, 11, func() { + wantAllocs(t, 10, func() { dl.Info("hello", "n", i, "s", s, "d", d, "n", i, "s", s, "d", d, diff --git a/src/log/slog/record.go b/src/log/slog/record.go index 82acc7ac7b..ea57c81c50 100644 --- a/src/log/slog/record.go +++ b/src/log/slog/record.go @@ -138,12 +138,11 @@ func (r *Record) Add(args ...any) { r.nFront++ } else { if r.back == nil { - r.back = make([]Attr, 0, countAttrs(args)) + r.back = make([]Attr, 0, countAttrs(args)+1) } r.back = append(r.back, a) } } - } // countAttrs returns the number of Attrs that would be created from args. -- 2.48.1