Skip to content

Commit

Permalink
trie: reduce allocs in recHash (ethereum#27770)
Browse files Browse the repository at this point in the history
# Conflicts:
#	trie/stacktrie.go
  • Loading branch information
MariusVanDerWijden authored and weiihann committed Dec 5, 2023
1 parent 1ddd337 commit 3e6c16a
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 9 deletions.
7 changes: 3 additions & 4 deletions trie/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,8 @@ func hexToCompact(hex []byte) []byte {
return buf
}

// hexToCompactInPlace places the compact key in input buffer, returning the length
// needed for the representation
func hexToCompactInPlace(hex []byte) int {
// hexToCompactInPlace places the compact key in input buffer, returning the compacted key.
func hexToCompactInPlace(hex []byte) []byte {
var (
hexLen = len(hex) // length of the hex input
firstByte = byte(0)
Expand All @@ -77,7 +76,7 @@ func hexToCompactInPlace(hex []byte) int {
hex[bi] = hex[ni]<<4 | hex[ni+1]
}
hex[0] = firstByte
return binLen
return hex[:binLen]
}

func compactToHex(compact []byte) []byte {
Expand Down
13 changes: 9 additions & 4 deletions trie/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ func TestHexToCompactInPlace(t *testing.T) {
} {
hexBytes, _ := hex.DecodeString(key)
exp := hexToCompact(hexBytes)
sz := hexToCompactInPlace(hexBytes)
got := hexBytes[:sz]
got := hexToCompactInPlace(hexBytes)
if !bytes.Equal(exp, got) {
t.Fatalf("test %d: encoding err\ninp %v\ngot %x\nexp %x\n", i, key, got, exp)
}
Expand All @@ -102,8 +101,7 @@ func TestHexToCompactInPlaceRandom(t *testing.T) {
hexBytes := keybytesToHex(key)
hexOrig := []byte(string(hexBytes))
exp := hexToCompact(hexBytes)
sz := hexToCompactInPlace(hexBytes)
got := hexBytes[:sz]
got := hexToCompactInPlace(hexBytes)

if !bytes.Equal(exp, got) {
t.Fatalf("encoding err \ncpt %x\nhex %x\ngot %x\nexp %x\n",
Expand All @@ -119,6 +117,13 @@ func BenchmarkHexToCompact(b *testing.B) {
}
}

func BenchmarkHexToCompactInPlace(b *testing.B) {
testBytes := []byte{0, 15, 1, 12, 11, 8, 16 /*term*/}
for i := 0; i < b.N; i++ {
hexToCompactInPlace(testBytes)
}
}

func BenchmarkCompactToHex(b *testing.B) {
testBytes := []byte{0, 15, 1, 12, 11, 8, 16 /*term*/}
for i := 0; i < b.N; i++ {
Expand Down
2 changes: 1 addition & 1 deletion trie/stacktrie.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ func (t *StackTrie) hash(st *stNode, path []byte) {

case leafNode:
st.key = append(st.key, byte(16))
n := shortNode{Key: hexToCompact(st.key), Val: valueNode(st.val)}
n := shortNode{Key: hexToCompactInPlace(st.key), Val: valueNode(st.val)}

n.encode(t.h.encbuf)
blob = t.h.encodedBytes()
Expand Down

0 comments on commit 3e6c16a

Please sign in to comment.