reduces amount of realloc calls in sstrsplit

Mon, 20 Feb 2017 17:28:58 +0100

author
Mike Becker <universe@uap-core.de>
date
Mon, 20 Feb 2017 17:28:58 +0100
changeset 235
7cf1e41833a2
parent 234
7a63b4986b5b
child 236
ffc6d0910342

reduces amount of realloc calls in sstrsplit

ucx/string.c file | annotate | diff | comparison | revisions
--- a/ucx/string.c	Mon Feb 20 17:12:14 2017 +0100
+++ b/ucx/string.c	Mon Feb 20 17:28:58 2017 +0100
@@ -218,7 +218,8 @@
     }
     
     ssize_t nmax = *n;
-    sstr_t* result = (sstr_t*) almalloc(allocator, sizeof(sstr_t));
+    size_t arrlen = 16;
+    sstr_t* result = (sstr_t*) almalloc(allocator, arrlen*sizeof(sstr_t));
 
     if (result) {
         sstr_t curpos = s;
@@ -250,17 +251,20 @@
 
                     /* allocate memory for the next string */
                     j++;
-                    sstr_t* reallocated = (sstr_t*)
-                            alrealloc(allocator, result, j*sizeof(sstr_t));
-                    if (reallocated) {
-                        result = reallocated;
-                    } else {
-                        for (ssize_t i = 0 ; i < j-1 ; i++) {
-                            alfree(allocator, result[i].ptr);
+                    if (j > arrlen) {
+                        arrlen *= 2;
+                        sstr_t* reallocated = (sstr_t*) alrealloc(
+                                allocator, result, arrlen*sizeof(sstr_t));
+                        if (reallocated) {
+                            result = reallocated;
+                        } else {
+                            for (ssize_t i = 0 ; i < j-1 ; i++) {
+                                alfree(allocator, result[i].ptr);
+                            }
+                            alfree(allocator, result);
+                            *n = -2;
+                            return NULL;
                         }
-                        alfree(allocator, result);
-                        *n = -2;
-                        return NULL;
                     }
                 } else {
                     /* nmax reached, copy the _full_ remaining string */

mercurial