From f588974a521d2626cba2a6ac3219c47eb3004aa1 Mon Sep 17 00:00:00 2001 From: surechen Date: Fri, 15 May 2020 22:59:38 +0800 Subject: [PATCH] math/big: reduce allocations for building decimal strings MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Append operations in the decimal String function may cause several allocations. Use make to pre allocate slices in String that have enough capacity to avoid additional allocations in append operations. name old time/op new time/op delta DecimalConversion-8 139µs ± 7% 109µs ± 2% -21.06% (p=0.000 n=10+10) Change-Id: Id0284d204918a179a0421c51c35d86a3408e1bd9 Reviewed-on: https://go-review.googlesource.com/c/go/+/233980 Run-TryBot: Emmanuel Odeke Run-TryBot: Giovanni Bajo TryBot-Result: Go Bot Reviewed-by: Giovanni Bajo Reviewed-by: Martin Möhrmann Reviewed-by: Robert Griesemer Trust: Giovanni Bajo Trust: Martin Möhrmann --- src/math/big/decimal.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/math/big/decimal.go b/src/math/big/decimal.go index ae9ffb5db6..716f03bfa4 100644 --- a/src/math/big/decimal.go +++ b/src/math/big/decimal.go @@ -166,18 +166,21 @@ func (x *decimal) String() string { switch { case x.exp <= 0: // 0.00ddd + buf = make([]byte, 0, 2+(-x.exp)+len(x.mant)) buf = append(buf, "0."...) buf = appendZeros(buf, -x.exp) buf = append(buf, x.mant...) case /* 0 < */ x.exp < len(x.mant): // dd.ddd + buf = make([]byte, 0, 1+len(x.mant)) buf = append(buf, x.mant[:x.exp]...) buf = append(buf, '.') buf = append(buf, x.mant[x.exp:]...) default: // len(x.mant) <= x.exp // ddd00 + buf = make([]byte, 0, x.exp) buf = append(buf, x.mant...) buf = appendZeros(buf, x.exp-len(x.mant)) } -- 2.48.1