]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: reduce allocations for building decimal strings
authorsurechen <surechen17@gmail.com>
Fri, 15 May 2020 14:59:38 +0000 (22:59 +0800)
committerRobert Griesemer <gri@golang.org>
Thu, 29 Oct 2020 22:45:29 +0000 (22:45 +0000)
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 <emmanuel@orijtech.com>
Run-TryBot: Giovanni Bajo <rasky@develer.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Giovanni Bajo <rasky@develer.com>
Reviewed-by: Martin Möhrmann <moehrmann@google.com>
Reviewed-by: Robert Griesemer <gri@golang.org>
Trust: Giovanni Bajo <rasky@develer.com>
Trust: Martin Möhrmann <moehrmann@google.com>

src/math/big/decimal.go

index ae9ffb5db6ab10526ccd1e855d2e63d35a825ca5..716f03bfa43398019aa67d65958b5c28ac141ee1 100644 (file)
@@ -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))
        }