state: optimize NEP17Balance serialization

Put to slice directly and allow to provide pre-allocated buffer.
```
BenchmarkNEP17BalanceBytes/stackitem-8         	 1712475	       673.4 ns/op	     448 B/op	       9 allocs/op
BenchmarkNEP17BalanceBytes/bytes-8             	13422715	        75.80 ns/op	      32 B/op	       2 allocs/op
BenchmarkNEP17BalanceBytes/bytes,_prealloc-8   	25990371	        46.46 ns/op	      16 B/op	       1 allocs/op
```

Signed-off-by: Evgeniy Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgeniy Stratonikov 2021-08-04 11:24:02 +03:00
parent b989504d74
commit 3218b74ea5
3 changed files with 66 additions and 3 deletions

View file

@ -0,0 +1,50 @@
package state
import (
"testing"
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
"github.com/stretchr/testify/require"
)
func TestNEP17Balance_Bytes(t *testing.T) {
var b NEP17Balance
b.Balance.SetInt64(0x12345678910)
data, err := stackitem.SerializeConvertible(&b)
require.NoError(t, err)
require.Equal(t, data, b.Bytes(nil))
t.Run("reuse buffer", func(t *testing.T) {
buf := make([]byte, 100)
ret := b.Bytes(buf[:0])
require.Equal(t, ret, buf[:len(ret)])
})
}
func BenchmarkNEP17BalanceBytes(b *testing.B) {
var bl NEP17Balance
bl.Balance.SetInt64(0x12345678910)
b.Run("stackitem", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, _ = stackitem.SerializeConvertible(&bl)
}
})
b.Run("bytes", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = bl.Bytes(nil)
}
})
b.Run("bytes, prealloc", func(b *testing.B) {
bs := bl.Bytes(nil)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = bl.Bytes(bs[:0])
}
})
}