From d2f002cb39bebdfac560282a43f3199c5d0903d7 Mon Sep 17 00:00:00 2001 From: korzhao Date: Sat, 21 Aug 2021 07:26:19 +0800 Subject: time/format: avoid growslice in time.String()/time.GoString() Pre-allocate the slice of buf with enough capacity to avoid growslice calls. benchmark old ns/op new ns/op delta BenchmarkTimeString-4 493 409 -17.12% BenchmarkTimeGoString-4 309 182 -41.30% benchmark old allocs new allocs delta BenchmarkTimeString-4 5 3 -40.00% BenchmarkTimeGoString-4 4 1 -75.00% benchmark old bytes new bytes delta BenchmarkTimeString-4 152 128 -15.79% BenchmarkTimeGoString-4 248 80 -67.74% Change-Id: I64eabe2ab0b3d4a846453c2e8e548a831d720b8c Reviewed-on: https://go-review.googlesource.com/c/go/+/343971 Run-TryBot: Ian Lance Taylor TryBot-Result: Go Bot Reviewed-by: Ian Lance Taylor Trust: Alexander Rakoczy --- src/time/format.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/time/format.go b/src/time/format.go index f4b4f48142..7ae89c557d 100644 --- a/src/time/format.go +++ b/src/time/format.go @@ -479,7 +479,7 @@ func (t Time) String() string { } m1, m2 := m2/1e9, m2%1e9 m0, m1 := m1/1e9, m1%1e9 - var buf []byte + buf := make([]byte, 0, 24) buf = append(buf, " m="...) buf = append(buf, sign) wid := 0 @@ -498,7 +498,8 @@ func (t Time) String() string { // GoString implements fmt.GoStringer and formats t to be printed in Go source // code. func (t Time) GoString() string { - buf := []byte("time.Date(") + buf := make([]byte, 0, 70) + buf = append(buf, "time.Date("...) buf = appendInt(buf, t.Year(), 0) month := t.Month() if January <= month && month <= December { -- cgit v1.2.3-54-g00ecf