From: Anders F Björklund Date: Sun, 12 Aug 2018 16:10:59 +0000 (+0200) Subject: Avoid using strcat and small realloc X-Git-Tag: v3.5~34^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=92f8b27d4e8fbeb618dfe23652cf868430617f4b;p=thirdparty%2Fccache.git Avoid using strcat and small realloc For performance reasons with large strings, we don't want to call strlen multiple times or to realloc one byte at a time. --- diff --git a/src/execute.c b/src/execute.c index e56526f17..c36f64166 100644 --- a/src/execute.c +++ b/src/execute.c @@ -358,11 +358,17 @@ format_command(char **argv) len += strlen(argv[i]); } len += 1; - char *buf = x_calloc(1, len + 1); + char *buf = x_malloc(len + 1); + char *p = buf; for (int i = 0; argv[i]; i++) { - strcat(buf, (i == 0) ? "" : " "); - strcat(buf, argv[i]); + if (i != 0) { + *p++ = ' '; + } + for (char *q = argv[i]; *q != '\0'; q++) { + *p++ = *q; + } } - strcat(buf, "\n"); + *p++ = '\n'; + *p++ = '\0'; return buf; } diff --git a/src/util.c b/src/util.c index d9143cea4..40e553ea4 100644 --- a/src/util.c +++ b/src/util.c @@ -35,8 +35,11 @@ static FILE *logfile; static char *logbuffer; +static size_t logbufsize; static size_t logsize; +#define LOGBUFSIZ 1024 + static bool init_log(void) { @@ -47,7 +50,8 @@ init_log(void) } assert(conf); if (conf->debug) { - logbuffer = x_calloc(1, 1); + logbufsize = LOGBUFSIZ; + logbuffer = x_malloc(logbufsize); logsize = 0; } if (str_eq(conf->log_file, "")) { @@ -68,11 +72,12 @@ static void append_log(const char *s, size_t len) { assert(logbuffer); - if (logsize + len > logsize) { - logbuffer = x_realloc(logbuffer, logsize + len + 1); - logsize = logsize + len; + if (logsize + len + 1 > logbufsize) { + logbufsize = logbufsize + len + 1 + LOGBUFSIZ; + logbuffer = x_realloc(logbuffer, logbufsize); } - strncat(logbuffer, s, len); + strncpy(logbuffer + logsize, s, len); + logsize += len; } static void