string: Speed up xvasprintf().
authorAndre Noll <maan@systemlinux.org>
Mon, 25 Mar 2013 19:05:05 +0000 (19:05 +0000)
committerAndre Noll <maan@systemlinux.org>
Thu, 2 May 2013 17:56:09 +0000 (19:56 +0200)
This avoids to call vsnprintf() twice in the common case where the
result is small.

The running time of a simple test case that called this function in
a loop improved from 13s to 8s due to this change.

string.c

index ba744bff2da640eed755fe14775e4f72b849766f..4d8b8b747201950ab4eb23caf85d8599dee94a26 100644 (file)
--- a/string.c
+++ b/string.c
@@ -136,15 +136,18 @@ __must_check __malloc char *para_strdup(const char *s)
 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
 {
        int ret;
 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
 {
        int ret;
-       size_t size;
+       size_t size = 150;
        va_list aq;
 
        va_list aq;
 
+       *result = para_malloc(size + 1);
        va_copy(aq, ap);
        va_copy(aq, ap);
-       ret = vsnprintf(NULL, 0, fmt, aq);
+       ret = vsnprintf(*result, size, fmt, aq);
        va_end(aq);
        assert(ret >= 0);
        va_end(aq);
        assert(ret >= 0);
+       if (ret < size) /* OK */
+               return ret;
        size = ret + 1;
        size = ret + 1;
-       *result = para_malloc(size);
+       *result = para_realloc(*result, size);
        va_copy(aq, ap);
        ret = vsnprintf(*result, size, fmt, aq);
        va_end(aq);
        va_copy(aq, ap);
        ret = vsnprintf(*result, size, fmt, aq);
        va_end(aq);