From 125e933da1ea370c0a87e4859e2e6e8b85d31fe2 Mon Sep 17 00:00:00 2001 From: jsvisa Date: Mon, 21 Jul 2025 17:30:01 +0800 Subject: [PATCH] triedb/pathdb: use binary.append to eliminate the tmp slice Signed-off-by: jsvisa --- triedb/pathdb/history_index_block.go | 30 ++++++++++++---------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/triedb/pathdb/history_index_block.go b/triedb/pathdb/history_index_block.go index 10cc88ed4e..91ef71ec25 100644 --- a/triedb/pathdb/history_index_block.go +++ b/triedb/pathdb/history_index_block.go @@ -221,17 +221,14 @@ func (br *blockReader) readGreaterThan(id uint64) (uint64, error) { type blockWriter struct { desc *indexBlockDesc // Descriptor of the block restarts []uint16 // Offsets into the data slice, marking the start of each section - scratch []byte // Buffer used for encoding full integers or value differences data []byte // Aggregated encoded data slice } func newBlockWriter(blob []byte, desc *indexBlockDesc) (*blockWriter, error) { - scratch := make([]byte, binary.MaxVarintLen64) if len(blob) == 0 { return &blockWriter{ - desc: desc, - scratch: scratch, - data: make([]byte, 0, 1024), + desc: desc, + data: make([]byte, 0, 1024), }, nil } restarts, data, err := parseIndexBlock(blob) @@ -241,7 +238,6 @@ func newBlockWriter(blob []byte, desc *indexBlockDesc) (*blockWriter, error) { return &blockWriter{ desc: desc, restarts: restarts, - scratch: scratch, data: data, // safe to own the slice }, nil } @@ -268,15 +264,12 @@ func (b *blockWriter) append(id uint64) error { // // The first element in a restart range is encoded using its // full value. - n := binary.PutUvarint(b.scratch[0:], id) - b.data = append(b.data, b.scratch[:n]...) + b.data = binary.AppendUvarint(b.data, id) } else { - // The current section is not full, append the element. // The element which is not the first one in the section // is encoded using the value difference from the preceding // element. - n := binary.PutUvarint(b.scratch[0:], id-b.desc.max) - b.data = append(b.data, b.scratch[:n]...) + b.data = binary.AppendUvarint(b.data, id-b.desc.max) } b.desc.entries++ @@ -392,11 +385,14 @@ func (b *blockWriter) full() bool { // // This function is safe to be called multiple times. func (b *blockWriter) finish() []byte { - var buf []byte - for _, number := range b.restarts { - binary.BigEndian.PutUint16(b.scratch[:2], number) - buf = append(buf, b.scratch[:2]...) + restartsLen := len(b.restarts) + buf := make([]byte, len(b.data)+restartsLen*2+1) + copy(buf, b.data) + + restartsOffset := len(b.data) + for i, restart := range b.restarts { + binary.BigEndian.PutUint16(buf[restartsOffset+2*i:], restart) } - buf = append(buf, byte(len(b.restarts))) - return append(b.data, buf...) + buf[len(buf)-1] = byte(restartsLen) + return buf }