From 07fec784e125ec6c506f158eca6b9c5e693d5f83 Mon Sep 17 00:00:00 2001 From: Nuno Cruces Date: Mon, 1 Sep 2025 11:57:33 +0100 Subject: [PATCH] Grow memory geometrically. (#316) --- internal/alloc/alloc_unix.go | 6 ++++-- internal/alloc/alloc_windows.go | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/internal/alloc/alloc_unix.go b/internal/alloc/alloc_unix.go index a00dbbf..157b544 100644 --- a/internal/alloc/alloc_unix.go +++ b/internal/alloc/alloc_unix.go @@ -40,9 +40,11 @@ func (m *mmappedMemory) Reallocate(size uint64) []byte { com := uint64(len(m.buf)) res := uint64(cap(m.buf)) if com < size && size <= res { - // Round up to the page size. + // Grow geometrically, round up to the page size. rnd := uint64(unix.Getpagesize() - 1) - new := (size + rnd) &^ rnd + new := com + com>>3 + new = min(max(size, new), res) + new = (new + rnd) &^ rnd // Commit additional memory up to new bytes. err := unix.Mprotect(m.buf[com:new], unix.PROT_READ|unix.PROT_WRITE) diff --git a/internal/alloc/alloc_windows.go b/internal/alloc/alloc_windows.go index 6bfc73a..2d753e2 100644 --- a/internal/alloc/alloc_windows.go +++ b/internal/alloc/alloc_windows.go @@ -47,9 +47,11 @@ func (m *virtualMemory) Reallocate(size uint64) []byte { com := uint64(len(m.buf)) res := uint64(cap(m.buf)) if com < size && size <= res { - // Round up to the page size. + // Grow geometrically, round up to the page size. rnd := uint64(windows.Getpagesize() - 1) - new := (size + rnd) &^ rnd + new := com + com>>3 + new = min(max(size, new), res) + new = (new + rnd) &^ rnd // Commit additional memory up to new bytes. _, err := windows.VirtualAlloc(m.addr, uintptr(new), windows.MEM_COMMIT, windows.PAGE_READWRITE)