From 8c31831626f3ca3417cf042cd63b215778d8aa94 Mon Sep 17 00:00:00 2001 From: Evgeniy Stratonikov Date: Tue, 17 Aug 2021 16:50:26 +0300 Subject: [PATCH] util: reduce allocations in `util.Uint256DecodeStringLE` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It is used a lot in clients (including our benchmark). `Uint160` is already optimized. ``` name old time/op new time/op delta Uint256DecodeStringLE-8 150ns ±15% 112ns ± 3% -25.23% (p=0.000 n=10+10) name old alloc/op new alloc/op delta Uint256DecodeStringLE-8 96.0B ± 0% 64.0B ± 0% -33.33% (p=0.000 n=10+10) name old allocs/op new allocs/op delta Uint256DecodeStringLE-8 2.00 ± 0% 1.00 ± 0% -50.00% (p=0.000 n=10+10) ``` Signed-off-by: Evgeniy Stratonikov --- pkg/util/uint256.go | 3 ++- pkg/util/uint256_test.go | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/pkg/util/uint256.go b/pkg/util/uint256.go index f3560b126..d7dd76aa2 100644 --- a/pkg/util/uint256.go +++ b/pkg/util/uint256.go @@ -26,7 +26,8 @@ func Uint256DecodeStringLE(s string) (u Uint256, err error) { if err != nil { return u, err } - return Uint256DecodeBytesLE(b) + slice.Reverse(b) + return Uint256DecodeBytesBE(b) } // Uint256DecodeStringBE attempts to decode the given string (in BE representation) diff --git a/pkg/util/uint256_test.go b/pkg/util/uint256_test.go index b1f5d2c3e..cbbeda216 100644 --- a/pkg/util/uint256_test.go +++ b/pkg/util/uint256_test.go @@ -95,3 +95,16 @@ func TestUint256_Serializable(t *testing.T) { var b util.Uint256 testserdes.EncodeDecodeBinary(t, &a, &b) } + +func BenchmarkUint256DecodeStringLE(b *testing.B) { + a := "f037308fa0ab18155bccfc08485468c112409ea5064595699e98c545f245f32d" + + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + _, err := util.Uint256DecodeStringLE(a) + if err != nil { + b.FailNow() + } + } +}