]> git.ipfire.org Git - thirdparty/ccache.git/commitdiff
Avoid using strcat and small realloc
authorAnders F Björklund <anders.f.bjorklund@gmail.com>
Sun, 12 Aug 2018 16:10:59 +0000 (18:10 +0200)
committerAnders F Björklund <anders.f.bjorklund@gmail.com>
Sun, 12 Aug 2018 16:14:39 +0000 (18:14 +0200)
For performance reasons with large strings, we don't want to
call strlen multiple times or to realloc one byte at a time.

src/execute.c
src/util.c

index e56526f175c8890ef5e9b0d3a8f926b430e9cb4a..c36f64166c856d0cc74fe7eb4623aeb0d1736f7b 100644 (file)
@@ -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;
 }
index d9143cea4211de153738f1b4cb9ce55c84c7a5f3..40e553ea4af2792186b2c277a505bf336e626bf5 100644 (file)
 
 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