From 3767574c7776d807e0ff0d67e5a3729ad765b97f Mon Sep 17 00:00:00 2001 From: Preston Van Loon Date: Fri, 3 Dec 2021 04:06:05 -0500 Subject: [PATCH] stateutil: Reduce allocations by specifying slice capacity eager (#9977) * Reduce allocations by specifying slice capacity eager * gofmt --- beacon-chain/state/stateutil/BUILD.bazel | 1 + .../state/stateutil/validator_root.go | 2 +- .../state/stateutil/validator_root_test.go | 22 +++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 beacon-chain/state/stateutil/validator_root_test.go diff --git a/beacon-chain/state/stateutil/BUILD.bazel b/beacon-chain/state/stateutil/BUILD.bazel index 67da4b457..24a9bf631 100644 --- a/beacon-chain/state/stateutil/BUILD.bazel +++ b/beacon-chain/state/stateutil/BUILD.bazel @@ -57,6 +57,7 @@ go_test( "state_root_test.go", "stateutil_test.go", "trie_helpers_test.go", + "validator_root_test.go", ], embed = [":go_default_library"], deps = [ diff --git a/beacon-chain/state/stateutil/validator_root.go b/beacon-chain/state/stateutil/validator_root.go index 8c88d4a14..cf0d67fb9 100644 --- a/beacon-chain/state/stateutil/validator_root.go +++ b/beacon-chain/state/stateutil/validator_root.go @@ -58,7 +58,7 @@ func ValidatorRootWithHasher(hasher ssz.HashFn, validator *ethpb.Validator) ([32 // a list of uint64 and mixed with registry limit. func Uint64ListRootWithRegistryLimit(balances []uint64) ([32]byte, error) { hasher := hash.CustomSHA256Hasher() - balancesMarshaling := make([][]byte, 0) + balancesMarshaling := make([][]byte, 0, len(balances)) for i := 0; i < len(balances); i++ { balanceBuf := make([]byte, 8) binary.LittleEndian.PutUint64(balanceBuf, balances[i]) diff --git a/beacon-chain/state/stateutil/validator_root_test.go b/beacon-chain/state/stateutil/validator_root_test.go new file mode 100644 index 000000000..7fc05e26e --- /dev/null +++ b/beacon-chain/state/stateutil/validator_root_test.go @@ -0,0 +1,22 @@ +package stateutil_test + +import ( + "testing" + + "github.com/prysmaticlabs/prysm/beacon-chain/state/stateutil" +) + +func BenchmarkUint64ListRootWithRegistryLimit(b *testing.B) { + balances := make([]uint64, 100000) + for i := 0; i < len(balances); i++ { + balances[i] = uint64(i) + } + b.Run("100k balances", func(b *testing.B) { + for i := 0; i < b.N; i++ { + _, err := stateutil.Uint64ListRootWithRegistryLimit(balances) + if err != nil { + b.Fatal(err) + } + } + }) +}