From a9a9a7c03402945b4a56aa1e8e4d42a075469c9c Mon Sep 17 00:00:00 2001 From: Daniel Liu Date: Mon, 16 Dec 2024 17:26:11 +0800 Subject: [PATCH] core/state: optimize some internals during encoding (#20038) --- common/bytes.go | 11 ++++++++ core/state/state_object.go | 2 +- core/state/state_object_test.go | 48 +++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 core/state/state_object_test.go diff --git a/common/bytes.go b/common/bytes.go index 703705ee3f067..9025e98b19a5d 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -132,3 +132,14 @@ func LeftPadBytes(slice []byte, l int) []byte { return padded } + +// TrimLeftZeroes returns a subslice of s without leading zeroes +func TrimLeftZeroes(s []byte) []byte { + idx := 0 + for ; idx < len(s); idx++ { + if s[idx] != 0 { + break + } + } + return s[idx:] +} diff --git a/core/state/state_object.go b/core/state/state_object.go index bb19597cc6f93..7eda5c4d4d75d 100644 --- a/core/state/state_object.go +++ b/core/state/state_object.go @@ -282,7 +282,7 @@ func (s *stateObject) updateTrie(db Database) Trie { continue } // Encoding []byte cannot fail, ok to ignore the error. - v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00")) + v, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) s.setError(tr.TryUpdate(key[:], v)) } return tr diff --git a/core/state/state_object_test.go b/core/state/state_object_test.go new file mode 100644 index 0000000000000..a5b28dec88f6f --- /dev/null +++ b/core/state/state_object_test.go @@ -0,0 +1,48 @@ +// Copyright 2019 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package state + +import ( + "bytes" + "testing" + + "github.com/XinFinOrg/XDPoSChain/common" +) + +func BenchmarkCutOriginal(b *testing.B) { + value := common.HexToHash("0x01") + for i := 0; i < b.N; i++ { + bytes.TrimLeft(value[:], "\x00") + } +} + +func BenchmarkCutsetterFn(b *testing.B) { + value := common.HexToHash("0x01") + cutSetFn := func(r rune) bool { + return int32(r) == int32(0) + } + for i := 0; i < b.N; i++ { + bytes.TrimLeftFunc(value[:], cutSetFn) + } +} + +func BenchmarkCutCustomTrim(b *testing.B) { + value := common.HexToHash("0x01") + for i := 0; i < b.N; i++ { + common.TrimLeftZeroes(value[:]) + } +}