Skip to content

Commit bbaf91e

Browse files
core/vm: improve memory resize (ethereum#33056)
Looks like (in some very EVM specific tests) we spent a lot of time resizing memory. If the underlying array is big enough, we can speed it up a bit by simply slicing the memory. goos: linux goarch: amd64 pkg: github.com/ethereum/go-ethereum/core/vm cpu: Intel(R) Core(TM) Ultra 7 155U │ /tmp/old.txt │ /tmp/new.txt │ │ sec/op │ sec/op vs base │ Resize-14 6.145n ± 9% 1.854n ± 14% -69.83% (p=0.000 n=10) │ /tmp/old.txt │ /tmp/new.txt │ │ B/op │ B/op vs base │ Resize-14 5.000 ± 0% 5.000 ± 0% ~ (p=1.000 n=10) │ /tmp/old.txt │ /tmp/new.txt │ │ allocs/op │ allocs/op vs base │ Resize-14 0.000 ± 0% 0.000 ± 0% ~ (p=1.000 n=10) ¹ From the blocktest benchmark: 620ms 10.93s (flat, cum) 9.92% of Total . . 80:func (m *Memory) Resize(size uint64) { 30ms 60ms 81: if uint64(m.Len()) < size { 590ms 10.87s 82: m.store = append(m.store, make([]byte, size-uint64(m.Len()))...) . . 83: } . . 84:} --------- Co-authored-by: Felix Lange <fjl@twurst.com>
1 parent 5320a1b commit bbaf91e

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

core/vm/memory.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ func (m *Memory) Free() {
4444
// To reduce peak allocation, return only smaller memory instances to the pool.
4545
const maxBufferSize = 16 << 10
4646
if cap(m.store) <= maxBufferSize {
47+
clear(m.store)
4748
m.store = m.store[:0]
4849
m.lastGasCost = 0
4950
memoryPool.Put(m)
@@ -76,10 +77,14 @@ func (m *Memory) Set32(offset uint64, val *uint256.Int) {
7677
val.PutUint256(m.store[offset:])
7778
}
7879

79-
// Resize resizes the memory to size
80+
// Resize grows the memory to the requested size.
8081
func (m *Memory) Resize(size uint64) {
81-
if uint64(m.Len()) < size {
82-
m.store = append(m.store, make([]byte, size-uint64(m.Len()))...)
82+
if uint64(len(m.store)) < size {
83+
if uint64(cap(m.store)) >= size {
84+
m.store = m.store[:size]
85+
} else {
86+
m.store = append(m.store, make([]byte, size-uint64(len(m.store)))...)
87+
}
8388
}
8489
}
8590

core/vm/memory_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,3 +83,10 @@ func TestMemoryCopy(t *testing.T) {
8383
}
8484
}
8585
}
86+
87+
func BenchmarkResize(b *testing.B) {
88+
memory := NewMemory()
89+
for i := range b.N {
90+
memory.Resize(uint64(i))
91+
}
92+
}

0 commit comments

Comments
 (0)