From 2e18e5dc6d8ad686e9c97b6fccdc91da79beb02c Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer Date: Mon, 16 Dec 2024 18:54:36 +0100 Subject: [PATCH] memory: Grow dynamic arrays by 50% Growing by a factor lower than the golden ratio increases the chances of reusing memory freed from earlier allocations. Set growth rate to 1.5 which also reduces internal fragmentation. --- include/private/memory.h | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/include/private/memory.h b/include/private/memory.h index caa4bb564..754803b15 100644 --- a/include/private/memory.h +++ b/include/private/memory.h @@ -31,6 +31,8 @@ xmlCleanupMemoryInternal(void); */ static XML_INLINE int xmlGrowCapacity(int capacity, size_t elemSize, int min, int max) { + int extra; + if (capacity <= 0) { #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION (void) min; @@ -44,10 +46,13 @@ xmlGrowCapacity(int capacity, size_t elemSize, int min, int max) { ((size_t) capacity > SIZE_MAX / 2 / elemSize)) return(-1); - if (capacity > max / 2) + /* Grow by 50% */ + extra = (capacity + 1) / 2; + + if (capacity > max - extra) return(max); - return(capacity * 2); + return(capacity + extra); } #endif /* XML_MEMORY_H_PRIVATE__ */