Skip to content

Commit 8dfd66f

Browse files
rlp: avoid list header allocation in encoder (#21274)
List headers made up 11% of all allocations during sync. This change removes most of those allocations by keeping the list header values cached in the encoder buffer instead. Since encoder buffers are pooled, list headers are no longer allocated in the common case where an encoder buffer is available for reuse. Co-authored-by: Felix Lange <fjl@twurst.com>
1 parent ec51cbb commit 8dfd66f

1 file changed

Lines changed: 14 additions & 15 deletions

File tree

‎rlp/encode.go‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,10 @@ func EncodeToReader(val interface{}) (size int, r io.Reader, err error) {
9292
}
9393

9494
type encbuf struct {
95-
str []byte // string data, contains everything except list headers
96-
lheads []*listhead // all list headers
97-
lhsize int // sum of sizes of all encoded list headers
98-
sizebuf []byte // 9-byte auxiliary buffer for uint encoding
95+
str []byte // string data, contains everything except list headers
96+
lheads []listhead // all list headers
97+
lhsize int // sum of sizes of all encoded list headers
98+
sizebuf []byte // 9-byte auxiliary buffer for uint encoding
9999
}
100100

101101
type listhead struct {
@@ -137,12 +137,8 @@ var encbufPool = sync.Pool{
137137

138138
func (w *encbuf) reset() {
139139
w.lhsize = 0
140-
if w.str != nil {
141-
w.str = w.str[:0]
142-
}
143-
if w.lheads != nil {
144-
w.lheads = w.lheads[:0]
145-
}
140+
w.str = w.str[:0]
141+
w.lheads = w.lheads[:0]
146142
}
147143

148144
// encbuf implements io.Writer so it can be passed it into EncodeRLP.
@@ -181,13 +177,16 @@ func (w *encbuf) encodeString(b []byte) {
181177
}
182178
}
183179

184-
func (w *encbuf) list() *listhead {
185-
lh := &listhead{offset: len(w.str), size: w.lhsize}
186-
w.lheads = append(w.lheads, lh)
187-
return lh
180+
// list adds a new list header to the header stack. It returns the index
181+
// of the header. The caller must call listEnd with this index after encoding
182+
// the content of the list.
183+
func (w *encbuf) list() int {
184+
w.lheads = append(w.lheads, listhead{offset: len(w.str), size: w.lhsize})
185+
return len(w.lheads) - 1
188186
}
189187

190-
func (w *encbuf) listEnd(lh *listhead) {
188+
func (w *encbuf) listEnd(index int) {
189+
lh := &w.lheads[index]
191190
lh.size = w.size() - lh.offset - lh.size
192191
if lh.size < 56 {
193192
w.lhsize++ // length encoded into kind tag

0 commit comments

Comments
 (0)