From f7988c9339787705a9a9b31da155a4c1ec95914e Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Sat, 24 Jan 2026 07:45:40 +0900 Subject: [PATCH] vm.c: use 1.5x stack growth instead of linear Change default stack growth from linear (+128) to exponential (1.5x). This reduces reallocation frequency while maintaining reasonable memory usage. The minimum growth is still MRB_STACK_GROWTH (128) to ensure small programs don't over-allocate. MRB_STACK_EXTEND_DOUBLING (2x growth) remains available for maximum performance when memory is not a concern. Co-authored-by: Claude --- doc/guides/mrbconf.md | 4 ++-- src/vm.c | 14 +++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/doc/guides/mrbconf.md b/doc/guides/mrbconf.md index 27c62671e..0b73a02c5 100644 --- a/doc/guides/mrbconf.md +++ b/doc/guides/mrbconf.md @@ -61,12 +61,12 @@ end `MRB_STACK_EXTEND_DOUBLING` - If defined doubles the stack size when extending it. -- Otherwise extends stack with `MRB_STACK_GROWTH`. +- Otherwise extends stack with 1.5x growth (minimum `MRB_STACK_GROWTH`). `MRB_STACK_GROWTH` - Default value is `128`. -- Used in stack extending. +- Minimum stack growth size when extending. - Ignored when `MRB_STACK_EXTEND_DOUBLING` is defined. `MRB_STACK_MAX` diff --git a/src/vm.c b/src/vm.c index f5e23be74..713160d48 100644 --- a/src/vm.c +++ b/src/vm.c @@ -169,13 +169,17 @@ stack_extend_alloc(mrb_state *mrb, mrb_int room) else size += room; #else - /* Use linear stack growth. + /* Use 1.5x stack growth. It is slightly slower than doubling the stack space, but it saves memory on small devices. */ - if (room <= MRB_STACK_GROWTH) - size += MRB_STACK_GROWTH; - else - size += room; + { + size_t newsize = size + (size >> 1); /* 1.5x growth */ + if (newsize < size + MRB_STACK_GROWTH) + newsize = size + MRB_STACK_GROWTH; + if (newsize < size + (size_t)room) + newsize = size + room; + size = newsize; + } #endif mrb_value *newstack = (mrb_value*)mrb_realloc(mrb, mrb->c->stbase, sizeof(mrb_value) * size);