From 210580bb0bbd14c02c2ba929012399ec32885de1 Mon Sep 17 00:00:00 2001 From: Vito Caputo Date: Mon, 14 Aug 2023 01:13:02 -0700 Subject: til_str: realloc in increasingly larger increments Typically people do a exponential style growth in such circumstances, but in my experience that tends to allocate nearly double what's needed quite often. Trying just a linearly increasing allocation size that bumps up the minimum amount every time a resize is triggered. If the needed amount exceeds the new growth increment, the larger value is used, but the growth rate still follows the minimum bump. I expect this to evolve more, just wanted to do something to speed up til_str a bit from it's naive approach. --- src/til_str.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/til_str.c b/src/til_str.c index 298e88d..4c8a0ad 100644 --- a/src/til_str.c +++ b/src/til_str.c @@ -18,7 +18,7 @@ struct til_str_t { struct { - size_t allocated, used; /* used is length, including '\0' terminator */ + size_t allocated, used, growby; /* used is length, including '\0' terminator */ } size; char *buf; }; @@ -38,6 +38,7 @@ static til_str_t * til_str_nulstr(size_t minsize) str->size.used = 1; str->size.allocated = MAX(minsize, TIL_STR_MIN_SIZE); + str->size.growby = TIL_STR_MIN_SIZE; str->buf = calloc(1, str->size.allocated); if (!str->buf) { @@ -88,7 +89,6 @@ til_str_t * til_str_newf(const char *format, ...) assert(format); - va_start(ap, format); str = til_str_nulstr(vsnprintf(NULL, 0, format, ap) + 1); va_end(ap); @@ -121,6 +121,9 @@ int til_str_appendf(til_str_t *str, const char *format, ...) if (str->size.used + len > str->size.allocated) { char *new; + str->size.growby += TIL_STR_MIN_SIZE; + len = MAX(str->size.growby, len); + new = realloc(str->buf, str->size.used + len); if (!new) return -ENOMEM; -- cgit v1.2.1