Skip to content

Commit a4bfc28

Browse files
authored
Merge pull request #2594 from CortexFoundation/dev
improve memory resize
2 parents 5df5fb7 + 44ddb2d commit a4bfc28

2 files changed

Lines changed: 15 additions & 3 deletions

File tree

core/vm/memory.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ func (m *Memory) Free() {
4646
// To reduce peak allocation, return only smaller memory instances to the pool.
4747
const maxBufferSize = 16 << 10
4848
if cap(m.store) <= maxBufferSize {
49+
clear(m.store)
4950
m.store = m.store[:0]
5051
m.lastGasCost = 0
5152
memoryPool.Put(m)
@@ -78,10 +79,14 @@ func (m *Memory) Set32(offset uint64, val *uint256.Int) {
7879
val.PutUint256(m.store[offset:])
7980
}
8081

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

core/vm/memory_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,10 @@ func TestMemoryCopy(t *testing.T) {
6767
}
6868
}
6969
}
70+
71+
func BenchmarkResize(b *testing.B) {
72+
memory := NewMemory()
73+
for i := range b.N {
74+
memory.Resize(uint64(i))
75+
}
76+
}

0 commit comments

Comments
 (0)