From b0744c2b2122bdd98898bab25e38bf2fdfb87529 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Wed, 1 Jun 2022 11:26:36 +0300 Subject: [PATCH] util: optimize MarshalJSON allocations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit name old time/op new time/op delta Uint256MarshalJSON-8 230ns ± 6% 83ns ±13% -63.78% (p=0.000 n=8+10) name old alloc/op new alloc/op delta Uint256MarshalJSON-8 320B ± 0% 80B ± 0% -75.00% (p=0.000 n=10+10) name old allocs/op new allocs/op delta Uint256MarshalJSON-8 5.00 ± 0% 1.00 ± 0% -80.00% (p=0.000 n=10+10) --- pkg/util/bench_test.go | 13 +++++++++++++ pkg/util/uint160.go | 7 ++++++- pkg/util/uint256.go | 7 ++++++- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 pkg/util/bench_test.go diff --git a/pkg/util/bench_test.go b/pkg/util/bench_test.go new file mode 100644 index 000000000..916d5b41e --- /dev/null +++ b/pkg/util/bench_test.go @@ -0,0 +1,13 @@ +package util + +import ( + "testing" +) + +func BenchmarkUint256MarshalJSON(b *testing.B) { + v := Uint256{0x01, 0x02, 0x03} + + for i := 0; i < b.N; i++ { + _, _ = v.MarshalJSON() + } +} diff --git a/pkg/util/uint160.go b/pkg/util/uint160.go index 3ac8d0eec..2f107e05e 100644 --- a/pkg/util/uint160.go +++ b/pkg/util/uint160.go @@ -132,7 +132,12 @@ func (u *Uint160) UnmarshalJSON(data []byte) (err error) { // MarshalJSON implements the json marshaller interface. func (u Uint160) MarshalJSON() ([]byte, error) { - return []byte(`"0x` + u.StringLE() + `"`), nil + r := make([]byte, 3+Uint160Size*2+1) + copy(r, `"0x`) + r[len(r)-1] = '"' + slice.Reverse(u[:]) // u is a copy, so we can mangle it in any way. + hex.Encode(r[3:], u[:]) + return r, nil } // UnmarshalYAML implements the YAML Unmarshaler interface. diff --git a/pkg/util/uint256.go b/pkg/util/uint256.go index 303ba5221..8886a261d 100644 --- a/pkg/util/uint256.go +++ b/pkg/util/uint256.go @@ -109,7 +109,12 @@ func (u *Uint256) UnmarshalJSON(data []byte) (err error) { // MarshalJSON implements the json marshaller interface. func (u Uint256) MarshalJSON() ([]byte, error) { - return []byte(`"0x` + u.StringLE() + `"`), nil + r := make([]byte, 3+Uint256Size*2+1) + copy(r, `"0x`) + r[len(r)-1] = '"' + slice.Reverse(u[:]) // u is a copy, so we can mangle it in any way. + hex.Encode(r[3:], u[:]) + return r, nil } // CompareTo compares two Uint256 with each other. Possible output: 1, -1, 0