state: optimize NEP17TransferLog.Append

Do not allocate a separate buffer for the transfer.
```
name                       old time/op    new time/op    delta
NEP17TransferLog_Append-8    58.8µs ± 3%    32.1µs ± 1%  -45.40%  (p=0.000 n=10+9)

name                       old alloc/op   new alloc/op   delta
NEP17TransferLog_Append-8     118kB ± 1%      44kB ± 3%  -63.00%  (p=0.000 n=9+10)

name                       old allocs/op  new allocs/op  delta
NEP17TransferLog_Append-8       901 ± 1%       513 ± 3%  -43.08%  (p=0.000 n=9+8)
```

Signed-off-by: Evgeniy Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgeniy Stratonikov 2021-08-05 12:59:08 +03:00
parent 403a4b75de
commit 23adb1e2fc

View file

@ -1,6 +1,7 @@
package state
import (
"bytes"
"math/big"
"github.com/nspcc-dev/neo-go/pkg/encoding/bigint"
@ -78,19 +79,20 @@ func (bs *NEP17TransferInfo) EncodeBinary(w *io.BinWriter) {
// Append appends single transfer to a log.
func (lg *NEP17TransferLog) Append(tr *NEP17Transfer) error {
w := io.NewBufBinWriter()
// The first entry, set up counter.
if len(lg.Raw) == 0 {
w.WriteB(1)
lg.Raw = append(lg.Raw, 0)
}
tr.EncodeBinary(w.BinWriter)
b := bytes.NewBuffer(lg.Raw)
w := io.NewBinWriterFromIO(b)
tr.EncodeBinary(w)
if w.Err != nil {
return w.Err
}
if len(lg.Raw) != 0 {
lg.Raw = b.Bytes()
lg.Raw[0]++
}
lg.Raw = append(lg.Raw, w.Bytes()...)
return nil
}