diff options
author | Vito Caputo <vcaputo@pengaru.com> | 2023-08-14 01:13:02 -0700 |
---|---|---|
committer | Vito Caputo <vcaputo@pengaru.com> | 2023-08-14 02:05:43 -0700 |
commit | 210580bb0bbd14c02c2ba929012399ec32885de1 (patch) | |
tree | b4172f1fffdb35e5782e4b976418d12f4ddebbf0 | |
parent | ff272ab570f376224a96f83d2f185ad3796a9155 (diff) |
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.
-rw-r--r-- | src/til_str.c | 7 |
1 files changed, 5 insertions, 2 deletions
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; |